CONTENTS

Chapter 5. Remote Objects

Periodically, the programming community starts thinking of "objects everywhere" as the solution to all its problems. The idea is to have a happy family of collaborating objects that can be located anywhere. These objects are, of course, supposed to communicate through standard protocols across a network. For example, you'll have an object on the client where the user can fill in a request for data. The client object sends a message to an object on the server that contains the details of the request. The server object gathers the requested information, perhaps by accessing a database or by communicating with additional objects. Once the server object has the answer to the client request, it sends the answer back to the client. Like most bandwagons in programming, this plan contains a fair amount of hype that can obscure the utility of the concept. This chapter:

Introduction to Remote Objects: The Roles of Client and Server

Let's go back to that idea of locally collecting information on a client computer and sending the information across the Net to a server. We are supposing that a user on a local machine will fill out an information request form. The form data gets sent to the vendor's server, and the server processes the request and will, in turn, want to send back product information the client can view, as shown in Figure 5-1.

Figure 5-1. Transmitting objects between client and server

graphics/05fig01.gif

In the traditional client/server model, the request is translated to an intermediary format (such as name/value pairs or XML data). The server parses the request format, computes the response, and formats the response for transmission to the client. The client then parses the response and displays it to the user.

But if your data is structured, then there is a significant coding hassle: you have to come up with appropriate ways of translating the data to and from the transmission format.

NOTE

graphics/note.gif
 

Another method for sending a request for data to a server is with HTML forms. Then, the client is simply the browser, and the server needs to gather the requested information and format it as HTML. Even in that model, it makes sense to separate the form processing from the data gathering. Typically, the form processing happens on the web server, and the data gathering happens on a different server, called an application server. You again have two communicating objects, the client object on the web server and the server object on the application server. This is a very common model in practice. In this chapter, we stick to a more traditional client/server example because it makes the roles of the client and server more intuitive.

What would go into a possible solution? Well, keeping in mind that objects sending requests to one another is the central tenet of OOP, we could put objects on different machines and have them send messages directly to each other. Let's assume that the client object was written in the Java programming language so that it can theoretically run anywhere. For the server objects, there are two obvious possibilities:

The first situation requires us to have a way for objects to talk to each other regardless of what language they were originally written in. If you think about it, you will agree with us that even the theoretical possibility of this is an amazing achievement. How can what is ultimately a sequence of bytes written in an arbitrary language, that we may have no knowledge of, tell us what services it offers, what messages it responds to? Of course, getting this to work in practice isn't easy, but the idea is elegant. The "common object request broker architecture," or CORBA standard, by the Object Management Group or OMG (www.omg.org) defines a common mechanism for interchanging data and discovering services.

The fundamental idea is that we delegate the task of finding out this information and activating any requested services to a so-called Object Request Broker (or ORB). You can think of an ORB as a kind of universal translator for interobject communication. Objects don't talk directly to each other. They always use an object broker to bargain between them. ORBs are located across the network, and it is important that they can communicate with each other. Most ORBs follow the specification set up by the OMG for inter-ORB communication. This specification is called the Internet Inter-ORB Protocol or IIOP.

NOTE

graphics/note.gif
 

Microsoft uses COM, a different, lower-level protocol for interobject communication. ORB-like services are bundled into the Windows operating system. As recently as 1999, Microsoft positioned COM as a competitor to CORBA. However, at the time of this writing, Microsoft is deemphasizing COM in favor of its NET model for XML-based communication between software components.

CORBA is completely language neutral. Client and server programs can be written in C++, the Java programming language, or any other language with a CORBA binding. You use an Interface Definition Language (or IDL) to specify the signatures of the messages and the types of the data your objects can send and understand. (IDL specifications look a lot like interfaces in the Java programming language; in fact, you can think of them as defining interfaces that the communicating objects must support. One nice feature of this model is that you can supply an IDL specification for an existing legacy object and then access its services through the ORB even if it was written long before the first ORB arrived.)

There are quite a few people who believe that CORBA is the object model of the future, and that the Java programming language is an excellent choice for implementing CORBA clients and servers. However, frankly speaking, CORBA has had a reputation—sometimes deserved—for slow performance, complex implementations, and interoperability problems. After running into quite a few CORBA problems while writing this chapter, and encountering many of the same issues when updating it two years later, our sentiments about CORBA are similar to those expressed by French president Charles De Gaulle's about Brazil: It has a great future … and always will.

If both communicating objects are written in the Java programming language, then the full generality and complexity of CORBA is not required. Sun developed a simpler mechanism, called Remote Method Invocation (RMI), specifically for communication between Java applications.

NOTE

graphics/note.gif
 

CORBA supporters initially did not like RMI because it completely ignored the CORBA standard. However, starting with SDK 1.3, CORBA and RMI have become more interoperable. In particular, you can use RMI with the IIOP protocol instead of the proprietary Java Remote Method Protocol. For more information on RMI over IIOP, see the introductory article at http://www.javaworld.com/javaworld/jw-12-1999/jw-12-iiop.html and the tutorial at http://java.sun.com/j2se/1.4/docs/guide/rmi-iiop/rmiiiopexample.html.

While CORBA may be interesting tomorrow, RMI is easier to understand and more convenient to use. For that reason, we will start out this chapter with RMI. Of course, RMI is useful only for communication between Java objects. In the last section of this chapter, we briefly introduce CORBA programming and show you how to hook up a C++ client with a server implemented in the Java programming language and a client implemented in the Java programming language with a C++ server.

Remote Method Invocations

The Remote Method Invocation mechanism lets you do something that sounds simple. If you have access to an object on a different machine, you can call methods of the remote object. Of course, the method parameters must somehow be shipped to the other machine, the object must be informed to execute the method, and the return value must be shipped back. RMI handles these details.

For example, the client seeking product information can query a Warehouse object on the server. It calls a remote method, find, which has one parameter: a Customer object. The find method returns an object to the client: the product information object. (See Figure 5-2.)

Figure 5-2. Invoking a remote method on a server object

graphics/05fig02.gif

In RMI terminology, the object whose method makes the remote call is called the client object. The remote object is called the server object. It is important to remember that the client/server terminology applies only to a single method call. The computer running the code in the Java programming language that calls the remote method is the client for that call, and the computer hosting the object that processes the call is the server for that call. It is entirely possible that the roles are reversed somewhere down the road. The server of a previous call can itself become the client when it invokes a remote method on an object residing on another computer.

Stubs and Parameter Marshalling

When client code wants to invoke a remote method on a remote object, it actually calls an ordinary method of the Java programming language that is encapsulated in a surrogate object called a stub. The stub resides on the client machine, not on the server. The stub packages the parameters used in the remote method into a block of bytes. This packaging uses a device-independent encoding for each parameter. For example, numbers are always sent in big-endian byte ordering. Objects are encoded with the serialization mechanism that is described in Chapter 12 of Volume 1. The process of encoding the parameters is called parameter marshalling. The purpose of parameter marshalling is to convert the parameters into a format suitable for transport from one virtual machine to another.

To sum up: the stub method on the client builds an information block that consists of:

The stub then sends this information to the server. On the server side, a receiver object performs the following actions for every remote method call:

The client stub unmarshals the return value or exception from the server. This value becomes the return value of the stub call. Or, if the remote method threw an exception, the stub rethrows it in the process space of the caller. Figure 5-3 shows the information flow of a remote method invocation.

Figure 5-3. Parameter marshalling

graphics/05fig03.gif

This process is obviously complex, but the good news is that it is completely automatic and, to a large extent, transparent for the programmer. Moreover, the designers of the remote Java object tried hard to give remote objects the same "look and feel" as local objects.

The syntax for a remote method call is the same as for a local call. If centralWarehouse is a stub object for a central warehouse object on a remote machine and getQuantity is the method you want to invoke on it, then a typical call looks like this:

centralWarehouse.getQuantity("SuperSucker 100 Vacuum Cleaner");

The client code always uses object variables whose type is an interface to access remote objects. For example, associated to this call would be an interface:

interface Warehouse
{
   int getQuantity(String description)
      throws RemoteException;
   . . .
}

An object declaration for a variable that will implement the interface is:

Warehouse centralWarehouse = . . .;

Of course, interfaces are abstract entities that only spell out what methods can be called along with their signatures. Variables whose type is an interface must always be bound to an actual object of some type. When calling remote methods, the object variable refers to a stub object. The client program does not actually know the type of those objects. The stub classes and the associated objects are created automatically.

While the designers did a good job of hiding many details of remote method invocation from the programmer, a number of techniques and caveats still must be mastered. Those programming tasks are the topic of the rest of this chapter.

NOTE

graphics/note.gif
 

Remote objects are garbage collected automatically, just as local objects are. However, the current distributed collector uses reference counting and cannot detect cycles of objects that refer to each other but have no external reference into the cycle. Cycles must be explicitly broken by the programmer before they can be reclaimed.

Dynamic Class Loading

When you pass a remote object to another program, either as a parameter or return value of a remote method, then that program must be able to deal with the associated stub object. That is, it must have the code for the stub class. The stub methods don't do a lot of interesting work. They just marshal and unmarshal the parameters and then contact the server for method calls. Of course, they do all this work transparently to the programmer.

Furthermore, the classes for parameters, return values, and exception objects may need to be loaded as well. This loading can be more complex than you might think. For example, you may declare a remote method with a certain return type that is known to the client, but the method actually returns an object of a subclass that is not known to the client. The class loader will then load that derived class.

While unglamorous, the stub classes must be available to the running client program. One obvious way to make these classes available is to put them on the local file system. However, if the server program is extended and new classes for return types and exceptions are added, then it would be a hassle to keep updating the client.

For that reason, RMI clients can automatically load stub classes from another place. The process is similar to the class loading process of applets that run in a browser.

Whenever a program loads new code from another network location, there is a security issue. For that reason, you need to use a security manager in RMI client applications. This is a safety mechanism that protects the program from viruses in stub code. For specialized applications, programmers can substitute their own class loaders and security managers, but those provided by the RMI system suffice for normal usage. (See Chapter 9 for more information on class loaders and security managers.)

Setting Up Remote Method Invocation

Running even the simplest remote object example requires quite a bit more setup than does running a standalone program or applet. You must run programs on both the server and client computers. The necessary object information must be separated into client-side interfaces and server-side implementations. There is also a special lookup mechanism that allows the client to locate objects on the server.

To get started with the actual coding, we walk through each of these requirements, using a simple example. In our first example, we generate a couple of objects of a type Product on the server computer. We then run a program on a client computer that locates and queries these objects.

NOTE

graphics/note.gif
 

You can try out this example on a single computer or on a pair of networked computers. We give you instructions for both scenarios.

Even if you run this code on a single computer, you must have network services available. In particular, be sure that you have TCP/IP running. If your computer doesn't have a network card, then you can activate TCP/IP by establishing a dialup networking connection.

Interfaces and Implementations

Your client program needs to manipulate server objects, but it doesn't actually have copies of them. The objects themselves reside on the server. The client code must still know what it can do with those objects. Their capabilities are expressed in an interface that is shared between the client and server and so resides simultaneously on both machines.

interface Product // shared by client and server
   extends Remote
{
   String getDescription() throws RemoteException;
}

Just as in this example, all interfaces for remote objects must extend the Remote interface defined in the java.rmi package. All the methods in those interfaces must also declare that they will throw a RemoteException. The reason for the declaration is that remote method calls are inherently less reliable than local calls—it is always possible that a remote call will fail. For example, the server or the network connection may be temporarily unavailable, or there may be a network problem. Your client code must be prepared to deal with these possibilities. For these reasons, the Java programming language forces you to catch the RemoteException with every remote method call and to specify the appropriate action to take when the call does not succeed.

The client accesses the server object through a stub that implements this interface.

Product p = ...;
   // see below how the client gets a stub
   // reference to a remote object
String d = p.getDescription();
System.out.println(d);

In the next section, you will see how the client can obtain a reference to this kind of remote object.

Next, on the server side, you must implement the class that actually carries out the methods advertised in the remote interface.

public class ProductImpl // server
   extends UnicastRemoteObject
   implements Product
{
   public ProductImpl(String d)
      throws RemoteException
   {
      descr = d;
   }

   public String getDescription()
      throws RemoteException
   {
      return "I am a " + descr + ". Buy me!";
   }

   private String descr;
}

NOTE

graphics/note.gif
 

The ProductImpl constructor is declared to throw a RemoteException because the UnicastRemoteObject might throw that exception if it can't connect to the network service that keeps track of server objects.

This class has a single method, getDescription, that can be called from the remote client.

You can tell that the class is a server for remote methods because it extends UnicastRemoteObject, which is a concrete Java platform class that makes objects remotely accessible.

NOTE

graphics/note.gif
 

The ProductImpl class is not a typical server class because it does so little work. Normally, you only want to have server classes that do some heavy-duty work that a client could not carry out locally. We just use the Product example to walk you through the mechanics of calling remote methods.

Server classes generally extend the class RemoteServer from the java.rmi.server package, but RemoteServer is an abstract class that defines only the basic mechanisms for the communication between server objects and their remote stubs. The UnicastRemoteObject class that comes with RMI extends the RemoteServer abstract class and is concrete—so you can use it without writing any code. The "path of least resistance" for a server class is to derive from UnicastRemoteObject, and all server classes in this chapter will do so. Figure 5-4 shows the inheritance relationship between these classes.

Figure 5-4. Inheritance diagram

graphics/05fig04.gif

A UnicastRemoteObject object resides on a server. It must be alive when a service is requested and must be reachable through the TCP/IP protocol. This is the class that we will be extending for all the server classes in this book and is the only server class available in the current version of the RMI package. Sun or third-party vendors may, in the future, design other classes for use by servers for RMI. For example, Sun is talking about a MulticastRemoteObject class for objects that are replicated over multiple servers. Other possibilities are for objects that are activated on demand or ones that can use other communications protocols, such as UDP.

NOTE

graphics/note.gif
 

Occasionally, you may not want a server class that extends the UnicastRemoteServer class, perhaps because it already extends another class. In that situation, you need to manually instantiate the server objects and pass them to the static exportObject method. Note that the server class must still implement a remote interface.

Remote server = new MyServer();
UnicastRemoteObject.exportObject(server, 0);

Alternatively, you can call

UnicastRemoteObject.exportObject(this, 0);

in the constructor. The second parameter is 0 to indicate that any suitable port can be used to listen to client connections.

When you use RMI (or any distributed object mechanism, for that matter), there is a somewhat bewildering set of classes to master. In this chapter, we use a uniform naming convention for all of our examples that, hopefully, makes it easier to recognize the purpose of each class. (See Table 5-1.)

Table 5-1. Naming conventions for RMI classes
No suffix (e.g., Product) A remote interface
Impl suffix (e.g., ProductImpl) A server class implementing that interface
Server suffix (e.g., ProductServer) A server program that creates server objects
Client suffix (e.g., ProductClient) A client program that calls remote methods
_Stub suffix (e.g., ProductImpl_Stub) A stub class that is automatically generated by the rmic program
_Skel suffix (e.g., ProductImpl_Skel) A skeleton class that is automatically generated by the rmic program; needed for SDK 1.1.

You need to generate stubs for the ProductImpl class. Recall that stubs are the classes that marshal (encode and send) the parameters and marshal the results of method calls across the network. The programmer never uses those classes directly. Moreover, they need not be written by hand. The rmic tool generates them automatically, as in the following example.

rmic -v1.2 ProductImpl

This call to the rmic tool generates a class file ProductImpl_Stub.class. If your class is in a package, you must call rmic with the full package name.

If your client uses SDK 1.1, you should instead call

rmic ProductImpl

Then, two files are generated: the stub file and a second class file named ProductImpl_Skel.class. This "skeleton" file is no longer necessary with the Java 2 platform.

NOTE

graphics/note.gif
 

Remember to first compile the source file with javac before running rmic. If you are generating stubs for a class in a package, you must give rmic the full package name.

Locating Server Objects

To access a remote object that exists on the server, the client needs a local stub object. How can the client request such a stub? The most common method is to call a remote method of another server object and to get a stub object as a return value. There is, however, a chicken-and-egg problem here. The first server object needs to be located some other way. The Sun RMI library provides a bootstrap registry service to locate the first server object.

A server program registers objects with the bootstrap registry service, and the client retrieves stubs to those objects. You register a server object by giving the bootstrap registry service a reference to the object and a name. The name is a string that is (hopefully) unique.

// server
ProductImpl p1 = new ProductImpl("Blackwell Toaster");
Naming.bind("toaster", p1);

The client code gets a stub to access that server object by specifying the server name and the object name in the following way:

// client
Product p
   = (Product)Naming.lookup("rmi://yourserver.com/toaster");

RMI URLs start with rmi:// and are followed by a server, an optional port number, another slash, and the name of the remote object. Another example is:

rmi://localhost:99/central_warehouse

By default, the port number is 1099.

NOTE

graphics/note.gif
 

Because it is notoriously difficult to keep names unique in a global registry, you should not use this technique as the general method for locating objects on the server. Instead, there should be relatively few named server objects registered with the bootstrap service. These should be objects that can locate other objects for you. In our example, we temporarily violate this rule and register relatively trivial objects to show you the mechanics for registering and locating objects.

For security reasons, an application can bind, unbind, or rebind registry objects references only if it runs on the same host as the registry. This prevents hostile clients from changing the registry information. However, any client can look up objects.

The code in Example 5-1 through Example 5-3 shows a complete server program that registers two Product objects under the names toaster and microwave.

TIP

graphics/tip.gif
 

If you compare our server with the server examples in the tutorial documentation, you will note that we do not install a security manager in the server. Contrary to the statements in the tutorial, a security manager is neither necessary nor particularly beneficial for RMI servers. Since adding a security manager yields yet another fertile source for configuration errors, we suggest that you only install a security manager if you want to constrain the actions in the server implementation or if the server is itself an RMI client of another server.

Example 5-1 ProductServer.java
 1. import java.rmi.*;
 2. import java.rmi.server.*;
 3.
 4. /**
 5.    This server program instantiates two remote objects,
 6.    registers them with the naming service, and waits for
 7.    clients to invoke methods on the remote objects.
 8. */
 9. public class ProductServer
10. {
11.    public static void main(String args[])
12.    {
13.       try
14.       {
15.          System.out.println
16.             ("Constructing server implementations...");
17.
18.          ProductImpl p1
19.             = new ProductImpl("Blackwell Toaster");
20.          ProductImpl p2
21.             = new ProductImpl("ZapXpress Microwave Oven");
22.
23.          System.out.println
24.             ("Binding server implementations to registry...");
25.
26.          Naming.rebind("toaster", p1);
27.          Naming.rebind("microwave", p2);
28.
29.          System.out.println
30.             ("Waiting for invocations from clients...");
31.       }
32.       catch(Exception e)
33.       {
34.          e.printStackTrace();
35.       }
36.    }
37. }
Example 5-2 ProductImpl.java
 1. import java.rmi.*;
 2. import java.rmi.server.*;
 3.
 4. /**
 5.    This is the implementation class for the remote product
 6.    objects.
 7. */
 8. public class ProductImpl
 9.    extends UnicastRemoteObject
10.    implements Product
11. {
12.    /**
13.       Constructs a product implementation
14.       @param n the product name
15.    */
16.    public ProductImpl(String n) throws RemoteException
17.    {
18.       name = n;
19.    }
20.
21.    public String getDescription() throws RemoteException
22.    {
23.       return "I am a " + name + ". Buy me!";
24.    }
25.
26.    private String name;
27. }
Example 5-3 Product.java
 1. import java.rmi.*;
 2.
 3. /**
 4.    The interface for remote product objects.
 5. */
 6. public interface Product extends Remote
 7. {
 8.    /**
 9.       Gets the description of this product.
10.       @return the product description
11.    */
12.    String getDescription() throws RemoteException;
13. }
Starting the server

Our server program isn't quite ready to run, yet. Because it uses the bootstrap RMI registry, that service must be available. To start the RMI registry under UNIX, you execute the statement

rmiregistry &

Under Windows, call

start rmiregistry

at a DOS prompt or from the Run dialog box. (The start command is a Windows command that starts a program in a new window.)

Now you are ready to start the server. Under UNIX, use the command:

java ProductServer &

Under Windows, use the command:

start java ProductServer

If you run the server program as

java ProductServer

then the program will never exit normally. This seems strange—after all, the program just creates two objects and registers them. Actually, the main function does exit immediately after registration, as you would expect. But, when you create an object of a class that extends UnicastRemoteObject, a separate thread is started that keeps the program alive indefinitely. Thus, the program stays around in order to allow clients to connect to it.

TIP

graphics/tip.gif
 

The Windows version of the SDK contains a command, javaw, that starts the bytecode interpreter as a separate Windows process and keeps it running. Some sources recommend that you use javaw, not start java, to run a Java session in the background in Windows for RMI. Doing so is not a good idea, for two reasons.

Windows has no tool to kill a javaw background process—it does not show up in the task list. It turns out that you need to kill and restart the bootstrap registry service when you change the stub of a registered class. To kill a process that you started with the start command, all you have to do is click on the window and press CTRL+C.

There is another important reason to use the start command. When you run a server process by using javaw, messages sent to the output or error streams are discarded. In particular, they are not displayed anywhere. If you want to see output or error messages, use start instead. Then, error messages at least show up on the console. And trust us, you will want to see these messages. There are lots of things that can go wrong when you experiment with RMI. The most common error is probably that you forget to run rmic. Then, the server complains about missing stubs. If you use javaw, you won't see that error message, and you'll scratch your head wondering why the client can't find the server objects.

Before writing the client program, let's verify that we succeeded in registering the remote objects. The Naming class has a method list that returns a list of all currently registered names. Example 5-4 shows a simple program that lists the names in the registry.

In our case, its output is

rmi:/toaster
rmi:/microwave
Example 5-4 ShowBindings.java
 1. import java.rmi.*;
 2. import java.rmi.server.*;
 3.
 4. /**
 5.    This programs shows all bindings in the naming service.
 6. */
 7. public class ShowBindings
 8. {
 9.    public static void main(String[] args)
10.    {
11.       try
12.       {
13.          String[] bindings = Naming.list("");
14.          for (int i = 0; i < bindings.length; i++)
15.             System.out.println(bindings[i]);
16.       }
17.       catch(Exception e)
18.       {
19.          e.printStackTrace();
20.       }
21.    }
22. }

The Client Side

Now, we can write the client program that asks each newly registered product object to print its description.

Client programs that use RMI should install a security manager to control the activities of the dynamically loaded stubs. The RMISecurityManager is such a security manager. You install it with the instruction

System.setSecurityManager(new RMISecurityManager());

NOTE

graphics/note.gif
 

If all classes (including stubs) are available locally, then you do not actually need a security manager. If you know all class files of your program at deployment time, you can deploy them all locally. However, it often happens that the server program evolves and new classes are added over time. Then you benefit from dynamic class loading. Any time you load code from another source, you need a security manager.

Applets already have a security manager which is able to control the stub classes. When using RMI from an applet, you do not install another security manager. However, for applications that are RMI clients, you should use the RMISecurityManager.

Example 5-5 shows the complete client program. The client simply obtains references to two Product objects in the RMI registry and invokes the getDescription method on both objects.

Example 5-5 ProductClient.java
 1. import java.rmi.*;
 2. import java.rmi.server.*;
 3.
 4. /**
 5.    This program demonstrates how to call a remote method
 6.    on two objects that are located through the naming service.
 7. */
 8. public class ProductClient
 9. {
10.    public static void main(String[] args)
11.    {
12.       System.setProperty("java.security.policy", "client.policy");
13.       System.setSecurityManager(new RMISecurityManager());
14.       String url = "rmi://localhost/";
15.          // change to "rmi://yourserver.com/"
16.          // when server runs on remote machine
17.          // yourserver.com
18.       try
19.       {
20.          Product c1 = (Product)Naming.lookup(url + "toaster");
21.          Product c2 = (Product)Naming.lookup(url + "microwave");
22.          System.out.println(c1.getDescription());
23.          System.out.println(c2.getDescription());
24.       }
25.       catch(Exception e)
26.       {
27.          e.printStackTrace();
28.       }
29.    }
30. }
Running the client

By default, the RMISecurityManager restricts all code in the program from establishing network connections. But the program needs to make network connections

NOTE

graphics/note.gif
 

Once the client program is deployed, it also needs permission to load its stub classes. We address this issue later when we discuss deployment.

To allow the client to connect to the RMI registry and the server object, you need to supply a policy file. We discuss policy files in greater detail in Chapter 9. For now, just use and modify the samples that we supply. Here is a policy file that allows an application to make any network connection to a port with port number at least 1024. (The RMI port is 1099 by default, and the server objects also use ports 1024.)

grant
{
   permission java.net.SocketPermission
      "*:1024-65535", "connect";
};

NOTE

graphics/note.gif
 

Multiple server objects on the same server can share a port. However, if a remote call is made and the port is busy, another port is opened automatically. Thus, you should expect somewhat fewer ports to be used than the remote objects on the server.

In the client program, we instruct the security manager to read the policy file, by setting the java.security.policy property to the file name.

System.setProperty("java.security.policy", "client.policy");

Alternatively, you can specify the system property setting on the command line:

java -Djava.security.policy=client.policy ProductClient

NOTE

graphics/note.gif
 

In SDK 1.1, a policy file was not required for RMI clients.

If the RMI registry and server are still running, you can proceed to run the client. Or, if you want to start from scratch, kill the RMI registry and the server. Then follow these steps:

  1. Compile the source files for the interface, implementation, client, and server classes.

    javac Product*.java
    
  2. Run rmic on the implementation class.

    rmic -v1.2 ProductImpl
    
  3. Start the RMI registry:

    rmiregistry &
    

    or

    start rmiregistry
    
  4. Start the server:

    java ProductServer &
    

    or

    start java ProductServer
    
  5. Run the client:

    java ProductClient
    

    (Make sure the client.policy file is in the current directory.)

The program simply prints

I am a Blackwell Toaster. Buy me!
I am a ZapXpress Microwave Oven. Buy me!

This output doesn't seem all that impressive, but consider what goes on behind the scenes when the client program executes the call to the getDescription method. The client program has a reference to a stub object that it obtained from the lookup method. It calls the getDescription method, which sends a network message to a receiver object on the server side. The receiver object invokes the getDescription method on the ProductImpl object located on the server. That method computes a string. The receiver sends that string across the network. The stub receives it and returns it as the result. See Figure 5-5.

Figure 5-5. Calling the remote getDescription method

graphics/05fig05.gif

java.rmi.Naming

graphics/api.gif
 

Preparing for Deployment

Deploying an application that uses RMI can be tricky because so many things can go wrong, and because the error messages that you get when something does go wrong are so poor. We have found that it really pays off to stage the deployment locally. In this preparatory step, separate the class files into three subdirectories:

server
download
client

The server directory contains all files that are needed to run the server. You will later move these files to the machine running the server process. In our example, the server directory contains the following files:

server:
   ProductServer.class
   ProductImpl.class
   Product.class
   ProductImpl_Stub.class

CAUTION

graphics/caution.gif
 

Add the stub classes to the server directory. They are needed when the server registers the implementation object. Contrary to popular belief, the server will not locate them in the download directory, even if you set the codebase.

The download directory contains those class files that will be loaded into the client, as well as the classes they depend on. In our example, you must add the following classes to the download directory:

download:
   ProductImpl_Stub.class
   Product.class

If your program was written with SDK 1.1, then you also need to supply the skeleton classes (such as ProductImpl_Skel.class). You will later place these files on a web server.

CAUTION

graphics/caution.gif
 

In addition to the interface stubs, your download directory must include the class files on which the stub files depend. This includes the remote interfaces (such as Product) and any classes or interfaces that occur as method parameter or return types. If you don't include those class files, then the server will mysteriously die when trying to register the server class.

Finally, the client directory contains the files that are needed to start the client. These are:

client:
   ProductClient.class
   Product.class
   client.policy

You will deploy these files on the client computer.

CAUTION

graphics/caution.gif
 

You must deploy the class files for the remote interfaces (such as Product) to the client. You must also deploy all class files on which these interfaces depend. If you don't, then the client will not load. It does not download these classes.

Now you have all class files partitioned correctly, and you can test that they can all be loaded.

We assume that you can start a web server on your computer. If you installed Tomcat to try out the servlet in Chapter 3, then simply use Tomcat and make the download directory a subdirectory of the webapps directory. Alternatively, you can get a lightweight server from ftp://java.sun.com/pub/jdk1.1/rmi/class-server.zip. That server is not a full-blown web server, but it is easier to install and has enough functionality to serve class files.

First, move the download directory into the web documents directory of the web server (or establish a symbolic link).

Next, edit the client.policy file. It must give the client these permissions:

Change the file to look like this:

grant
{
   permission java.net.SocketPermission
      "*:1024-65535", "connect";
   permission java.net.SocketPermission
      "*:80", "connect";
};

Finally, you are ready to test your setup.

  1. Start the web server.

  2. Start a new shell. Make sure that the class path is not set to anything. Change to a directory that contains no class files. Then start the RMI registry.

    CAUTION

    graphics/caution.gif
     

    If you just want to test out your program and have client, server, and stub class files in a single directory, then you can start the RMI registry in that directory. However, for deployment, make sure to start the registry in a shell with no class path and in a directory with no class files. Otherwise, the RMI registry may find spurious class files which will confuse it when it should download additional classes from a different source. There is a reason for this behavior; see http://java.sun.com/products/jdk/1.2/docs/guide/rmi/codebase.html. In a nutshell, each stub object is annotated with the code base from which supporting classes can be downloaded. If the RMI registry finds the class on its class path, that codebase annotation is empty, and supporting classes will not be located from another source.

    RMI registry confusion is a major source of grief for RMI deployment. The easiest way of protecting yourself is to make sure that the RMI registry cannot find any classes.

     

  3. Start a new shell. Change to the server directory. Start the server, giving a URL to the download directory as the value of the java.rmi.server.codebase property:

    java
       -Djava.rmi.server.codebase=http://localhost/download/
       ProductServer &
    

    If you use Tomcat, you need to use the URL

    http://localhost:8080/download/

    CAUTION

    graphics/caution.gif
     

    It is very important that you make sure that the URL ends with a slash (/).

  4. Change to the client directory. Make sure the client.policy file is in that directory. Start the client.

    java -Djava.security.policy=client.policy ProductClient
    

If both the server and the client started up without a hitch, then you are ready to go to the next step and deploy the classes on a separate client and server. If not, you need to do some more tweaking.

TIP

graphics/tip.gif
 

If you do not want to install a web server locally, you can use a file URL to test class loading. However, the setup is a bit trickier. Add the line

permission java.io.FilePermission
   "downloadDirectory", "read";

to your client policy file. Here, the download directory is the full path name to the download directory, enclosed in quotes, and ending in a minus sign (to denote all files in that directory and its subdirectories). In Windows file names, you have to double each backslash. For example,

permission java.io.FilePermission
  "/home/test/download/-", "read";

or (under Windows)

permission java.io. FilePermission
  "c:\\home\\test\\download\\-", "read";

Start the RMI registry, then the server with

java -Djava.rmi.server.codebase=file://home/test/download/
   ProductServer &

or

start java
   -Djava.rmi.server.codebase=file:/c:\home\test\download/
   ProductServer

(Remember to add a slash at the end of the URL.) Then start the client.

Deploying the Program

Now that you have tested the deployment of your program, you are ready to distribute it onto the actual clients and servers.

Move the classes in the download directory to the web server. Make sure to use that URL when starting the server. Move the classes in the server directory onto your server and start the RMI registry and the server.

Your server setup is now finalized. But you need to make two changes in the client. First, edit the policy file and replace * with your server name:

grant
{
   permission java.net.SocketPermission
      "yourserver.com:1024-65535", "connect";
   permission java.net.SocketPermission
      "yourserver.com:80", "connect";
};

Finally, replace localhost in the RMI URL of the client program with the actual server.

String url = "rmi://yourserver.com/";
Product c1 = (Product)Naming.lookup(url + "toaster");
. . .

Then, recompile the client and try it. If everything works, then congratulations are in order. If not, you may find the following sidebar helpful. It contains a checklist of a number of problems that can commonly arise when trying to get RMI to work.

TIP

graphics/tip.gif
 

In practice, you would not want to hard code the RMI URLs into your program. Instead, you can store them in a property file. We will use that technique in Example 5-13.

RMI Deployment Checklist

Deploying RMI is tough because it either works, or it fails with a very cryptic error message. Judging from the traffic on the RMI discussion list at http://archives.java.sun.com/archives/rmi-users.html, many programmers initially run into grief. If you do too, you may find it helpful to check out the following issues. We managed to get every one of them wrong at least once during testing.

  • Did you put the stub class files into the server directory?

  • Did you put the interface class files into the download and client directory?

  • Did you include the dependent classes for each class? For example, in the next section, you will see an interface Warehouse that has a method with a parameter of type Customer. Be sure to include Customer.class whenever you deploy Warehouse.class.

  • When starting rmiregistry, was the CLASSPATH unset? Was the current directory free from class files?

  • Do you use a policy file when starting the client? Does the policy file contain the correct server names (or * to connect to any host)?

  • If you use a file: URL for testing, do you specify the correct file name in the policy file? Does it end in a /- or \\- ? Did you remember to use \\ for Windows file names?

  • Does your codebase URL end in a slash?

Finally, note that the RMI registry remembers the class files that it found as well as those that it failed to find. If you keep adding or removing various class files to test which files are really necessary, make sure to restart rmiregistry each time.

Parameter Passing in Remote Methods

You often want to pass parameters to remote objects. This section explains some of the techniques for doing so—along with some of the pitfalls.

Passing Nonremote Objects

When a remote object is passed from the server to the client, the client receives a stub. Using the stub, it can manipulate the server object by invoking remote methods. The object, however, stays on the server. It is also possible to pass and return any objects via a remote method call, not just those that implement the Remote interface. For example, the getDescription method of the preceding section returned a String object. That string was created on the server and had to be transported to the client. Since String does not implement the Remote interface, the client cannot return a string stub object. Instead, the client gets a copy of the string. Then, after the call, the client has its own String object to work with. This means that there is no need for any further connection to any object on the server to deal with that string.

Whenever an object that is not a remote object needs to be transported from one Java virtual machine to another, the Java virtual machine makes a copy and sends that copy across the network connection. This technique is very different from parameter passing in a local method. When you pass objects into a local method or return them as method results, only object references are passed. However, object references are memory addresses of objects in the local Java virtual machine. This information is meaningless to a different Java virtual machine.

It is not difficult to imagine how a copy of a string can be transported across a network. The RMI mechanism can also make copies of more complex objects, provided they are serializable. RMI uses the serialization mechanism described in Chapter 12 of Volume 1 to send objects across a network connection. This means that only the information in any classes that implement the Serializable interface can be copied. The following program shows the copying of parameters and return values in action. This program is a simple application that lets a user shop for a gift. On the client, the user runs a program that gathers information about the gift recipient, in this case, age, sex, and hobbies (see Figure 5-6).

Figure 5-6. Obtaining product suggestions from the server

graphics/05fig06.gif

An object of type Customer is then sent to the server. Since Customer is not a remote object, a copy of the object is made on the server. The server program sends back an array list of products. The array list contains those products that match the customer profile, and it always contains that one item that will delight anyone, namely, a copy of the book Core Java. Again, ArrayList is not a remote class, so the array list is copied from the server back to its client. As described in Chapter 12 of volume 1, the serialization mechanism makes copies of all objects that are referenced inside a copied object. In our case, it makes a copy of all array list entries as well. We added an extra complexity: the entries are actually remote Product objects. Thus, the recipient gets a copy of the array list, filled with stub objects to the products on the server (see Figure 5-7).

Figure 5-7. Copying local parameter and result objects

graphics/05fig07.gif

To summarize, remote objects are passed across the network as stubs. Nonremote objects are copied. All of this is automatic and requires no programmer intervention.

Whenever code calls a remote method, the stub makes a package that contains copies of all parameter values and sends it to the server, using the object serialization mechanism to marshal the parameters. The server unmarshals them. Naturally, the process can be quite slow—especially when the parameter objects are large.

Let's look at the complete program. First, we have the interfaces for the product and warehouse services, as shown in Example 5-6 and Example 5-7.

Example 5-6 Product.java
 1. import java.rmi.*;
 2.
 3. /**
 4.    The interface for remote product objects.
 5. */
 6. public interface Product extends Remote
 7. {
 8.    /**
 9.       Gets the description of this product.
10.       @return the product description
11.    */
12.    String getDescription() throws RemoteException;
13.
14.    final int MALE = 1;
15.    final int FEMALE = 2;
16.    final int BOTH = MALE + FEMALE;
17. }
Example 5-7 Warehouse.java
 1. import java.rmi.*;
 2. import java.util.*;
 3.
 4. /**
 5.    The remote interface for a warehouse with products.
 6. */
 7. public interface Warehouse extends Remote
 8. {
 9.    /**
10.       Gets products that are good matches for a customer.
11.       @param c the customer to match
12.       @return an array list of matching products
13.    */
14.    ArrayList find(Customer c) throws RemoteException;
15. }

Example 5-8 shows the implementation for the product service. Products store a description, an age range, the gender targeted (male, female, or both), and the matching hobby. Note that this class implements the getDescription method advertised in the Product interface, and it also implements another method, match, which is not a part of that interface. The match method is an example of a local method, a method that can be called only from the local program, not remotely. Since the match method is local, it need not be prepared to throw a RemoteException.

Example 5-9 contains the code for the Customer class. Note once again that Customer is not a remote class—none of its methods can be executed remotely. However, the class is serializable. Therefore, objects of this class can be transported from one virtual machine to another.

Examples 5-10 and 5-11 shows the interface and implementation for the warehouse service. Like the ProductImpl class, the WarehouseImpl class has local and remote methods. The add and read methods are local; they are used by the server to add products to the warehouse. The find method is remote; it is used to find items in the warehouse.

To illustrate that the Customer object is actually copied, the find method of the WarehouseImpl class clears the customer object it receives. When the remote method returns, the WarehouseClient displays the customer object that it sent to the server. As you will see, that object has not changed. The server cleared only its copy. In this case, the reset operation serves no useful purpose except to demonstrate that local objects are copied when they are passed as parameters.

In general, the methods of server classes such as ProductImpl and WarehouseImpl should be synchronized. Then, it is possible for multiple client stubs to make simultaneous calls to a server object, even if some of the methods change the state of the server. (See Chapter 2 for more details on synchronized methods.) In Example 5-11, we synchronize the methods of the WarehouseImpl class because it is conceivable that the local add and the remote find methods are called simultaneously. We don't synchronize the methods of the ProductImpl class because the product server objects don't change their state. Example 5-12 shows the server program that creates a warehouse object and registers it with the bootstrap registry service.

NOTE

graphics/note.gif
 

Remember that you must start the registry and the server program and keep both running before you start the client.

Example 5-13 shows the code for the client. When the user clicks on the "Submit" button, a new customer object is generated and passed to the remote find method. Then, the customer record is displayed in the text area (to prove that the clear call in the server did not affect it). Finally, the product descriptions of the returned products in the array list are added to the text area. Note that each getDescription call is again a remote method invocation. That would not be a good design in practice—you would normally pass small objects such as product descriptions by value. But we want to demonstrate that a remote object is automatically replaced by a stub during marshalling.

TIP

graphics/tip.gif
 

If you start the server with

java -Djava.rmi.server.logCalls=true WarehouseServer &

then the server logs all remote method calls on its console. Try it—you'll get a good impression of the RMI traffic.

Example 5-8 ProductImpl.java
 1. import java.rmi.*;
 2. import java.rmi.server.*;
 3.
 4. /**
 5.    This is the implementation class for the remote product
 6.    objects.
 7. */
 8. public class ProductImpl
 9.    extends UnicastRemoteObject
10.    implements Product
11. {
12.    /**
13.       Constructs a product implementation
14.       @param n the product name
15.       @param s the suggested sex (MALE, FEMALE, or BOTH)
16.       @param age1 the lower bound for the suggested age
17.       @param age2 the upper bound for the suggested age
18.       @param h the hobby matching this product
19.    */
20.    public ProductImpl(String n, int s, int age1, int age2,
21.       String h) throws RemoteException
22.    {
23.       name = n;
24.       ageLow = age1;
25.       ageHigh = age2;
26.       sex = s;
27.       hobby = h;
28.    }
29.
30.    /**
31.       Checks whether this product is a good match for a
32.       customer. Note that this method is a local method since
33.       it is not part of the Product interface.
34.       @param c the customer to match against this product
35.       @return true if this product is appropriate for the
36.       customer
37.    */
38.    public boolean match(Customer c)
39.    {
40.       if (c.getAge() < ageLow || c.getAge() > ageHigh)
41.          return false;
42.       if (!c.hasHobby(hobby)) return false;
43.       if ((sex & c.getSex()) == 0) return false;
44.       return true;
45.    }
46.
47.    public String getDescription() throws RemoteException
48.    {
49.       return "I am a " + name + ". Buy me!";
50.    }
51.
52.    private String name;
53.    private int ageLow;
54.    private int ageHigh;
55.    private int sex;
56.    private String hobby;
57. }
Example 5-9 Customer.java
 1. import java.io.*;
 2.
 3. /**
 4.    Description of a customer. Note that customer objects are not
 5.    remote--the class does not implement a remote interface.
 6. */
 7. public class Customer implements Serializable
 8. {
 9.    /**
10.       Constructs a customer.
11.       @param theAge the customer's age
12.       @param theSex the customer's sex (MALE or FEMALE)
13.       @param theHobbies the customer's hobbies
14.    */
15.    public Customer(int theAge, int theSex, String[] theHobbies)
16.    {
17.       age = theAge;
18.       sex = theSex;
19.       hobbies = theHobbies;
20.    }
21.
22.    /**
23.       Gets the customer's age.
24.       @return the age
25.    */
26.    public int getAge() { return age; }
27.
28.    /**
29.       Gets the customer's sex
30.       @return MALE or FEMALE
31.    */
32.    public int getSex() { return sex; }
33.
34.    /**
35.       Tests whether this customer has a particular hobby.
36.       @param aHobby the hobby to test
37.       @return true if this customer has the hobby
38.    */
39.    public boolean hasHobby(String aHobby)
40.    {
41.       if (aHobby == "") return true;
42.       for (int i = 0; i < hobbies.length; i++)
43.          if (hobbies[i].equals(aHobby)) return true;
44.
45.       return false;
46.    }
47.
48.    /**
49.       Resets this customer record to default values.
50.    */
51.    public void reset()
52.    {
53.       age = 0;
54.       sex = 0;
55.       hobbies = null;
56.    }
57.
58.    public String toString()
59.    {
60.       String result = "Age: " + age + ", Sex: ";
61.       if (sex == Product.MALE) result += "Male";
62.       else if (sex == Product.FEMALE) result += "Female";
63.       else result += "Male or Female";
64.       result += ", Hobbies:";
65.       for (int i = 0; i < hobbies.length; i++)
66.          result += " " + hobbies[i];
67.       return result;
68.    }
69.
70.    private int age;
71.    private int sex;
72.    private String[] hobbies;
73. }
Example 5-10 Warehouse.java
 1. import java.rmi.*;
 2. import java.util.*;
 3.
 4. /**
 5.    The remote interface for a warehouse with products.
 6. */
 7. public interface Warehouse extends Remote
 8. {
 9.    /**
10.       Gets products that are good matches for a customer.
11.       @param c the customer to match
12.       @return an array list of matching products
13.    */
14.    ArrayList find(Customer c) throws RemoteException;
15. }
Example 5-11 WarehouseImpl.java
 1. import java.io.*;
 2. import java.rmi.*;
 3. import java.util.*;
 4. import java.rmi.server.*;
 5. import java.util.*;
 6.
 7. /**
 8.    This class is the implementation for the remote
 9.    Warehouse interface.
10. */
11. public class WarehouseImpl
12.    extends UnicastRemoteObject
13.    implements Warehouse
14. {
15.    /**
16.       Constructs a warehouse implementation.
17.    */
18.    public WarehouseImpl()
19.       throws RemoteException
20.    {
21.       products = new ArrayList();
22.       coreJavaBook = new ProductImpl("Core Java Book",
23.          0, 200, Product.BOTH, "Computers");
24.    }
25.
26.    /**
27.       Reads in a set of product descriptions. Each line has t
28.       the format
29.       name|sex|age1|age2|hobby, e.g.
30.       Blackwell Toaster|BOTH|18|200|Household
31.       @param reader the reader to read from
32.    */
33.    public void read(BufferedReader reader) throws IOException
34.    {
35.       String line;
36.       while ((line = reader.readLine()) != null)
37.       {
38.          StringTokenizer tokenizer = new StringTokenizer(line,
39.             "|");
40.          String name = tokenizer.nextToken();
41.          String s = tokenizer.nextToken();         
42.          int sex = 0;
43.          if (s.equals("MALE")) sex = Product.MALE;
44.          else if (s.equals("FEMALE")) sex = Product.FEMALE;
45.          else if (s.equals("BOTH")) sex = Product.BOTH;
46.          int age1 = Integer.parseInt(tokenizer.nextToken());
47.          int age2 = Integer.parseInt(tokenizer.nextToken());
48.          String hobby = tokenizer.nextToken();
49.          add(new ProductImpl(name, sex, age1, age2, hobby));
50.       }
51.    }
52.
53.    /**
54.       Add a product to the warehouse. Note that this is a local
55.       method.
56.       @param p the product to add
57.    */
58.    public synchronized void add(ProductImpl p)
59.    {
60.       products.add(p);
61.    }
62.
63.    public synchronized ArrayList find(Customer c)
64.       throws RemoteException
65.    {
66.       ArrayList result = new ArrayList();
67.       // add all matching products
68.       for (int i = 0; i < products.size(); i++)
69.       {
70.          ProductImpl p = (ProductImpl)products.get(i);
71.          if (p.match(c)) result.add(p);
72.       }
73.       // add the product that is a good match for everyone
74.       result.add(coreJavaBook);
75.
76.       // we reset c just to show that c is a copy of the
77.       // client object
78.       c.reset();
79.       return result;
80.    }
81.
82.    private ArrayList products;
83.    private ProductImpl coreJavaBook;
84. }
Example 5-12 WarehouseServer.java
 1. import java.io.*;
 2. import java.rmi.*;
 3. import java.rmi.server.*;
 4.
 5. /**
 6.    This server program instantiates a remote warehouse
 7.    objects, registers it with the naming service, and waits
 8.    for clients to invoke methods.
 9. */
10. public class WarehouseServer
11. {
12.    public static void main(String[] args)
13.    {
14.       try
15.       {
16.          System.out.println
17.             ("Constructing server implementations...");
18.
19.          WarehouseImpl w = new WarehouseImpl();
20.          w.read(new BufferedReader(new
21.             FileReader("products.dat")));
22.
23.          System.out.println
24.             ("Binding server implementations to registry...");
25.
26.          Naming.rebind("central_warehouse", w);
27.
28.          System.out.println
29.             ("Waiting for invocations from clients...");
30.        }
31.        catch(Exception e)
32.        {
33.           e.printStackTrace();
34.        }
35.    }
36. }
Example 5-13 WarehouseClient.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.io.*;
  4. import java.rmi.*;
  5. import java.rmi.server.*;
  6. import java.util.*;
  7. import javax.swing.*;
  8.
  9. /**
 10.    The client for the warehouse program.
 11. */
 12. public class WarehouseClient
 13. {
 14.    public static void main(String[] args)
 15.    {
 16.       System.setProperty("java.security.policy", "client.policy");
 17.       System.setSecurityManager(new RMISecurityManager());
 18.       JFrame frame = new WarehouseClientFrame();
 19.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 20.       frame.show();
 21.    }
 22. }
 23.
 24. /**
 25.    A frame to select the customer's age, sex, and hobbies, and to
 26.    show the matching products resulting from a remote call to the
 27.    warehouse.
 28. */
 29. class WarehouseClientFrame extends JFrame
 30. {
 31.    public WarehouseClientFrame()
 32.    {
 33.       setTitle("WarehouseClient");
 34.       setSize(WIDTH, HEIGHT);
 35.       initUI();
 36.
 37.       try
 38.       {
 39.          Properties props = new Properties();
 40.          String fileName = "WarehouseClient.properties";
 41.          FileInputStream in = new FileInputStream(fileName);
 42.          props.load(in);
 43.          String url = props.getProperty("warehouse.url");
 44.          if (url == null)
 45.             url = "rmi://localhost/central_warehouse";
 46.
 47.          centralWarehouse = (Warehouse)Naming.lookup(url);
 48.       }
 49.       catch(Exception e)
 50.       {
 51.        System.out.println("Error: Can't connect to warehouse. " + e);
 52.       }
 53.    }
 54.
 55.    /**
 56.       Initializes the user interface.
 57.    */
 58.    private void initUI()
 59.    {
 60.       getContentPane().setLayout(new GridBagLayout());
 61.
 62.       GridBagConstraints gbc = new GridBagConstraints();
 63.       gbc.fill = GridBagConstraints.HORIZONTAL;
 64.       gbc.weightx = 100;
 65.       gbc.weighty = 0;
 66.
 67.       add(new JLabel("Age:"), gbc, 0, 0, 1, 1);
 68.       age = new JTextField(4);
 69.       age.setText("20");
 70.       add(age, gbc, 1, 0, 1, 1);
 71.
 72.       male = new JCheckBox("Male", true);
 73.       female = new JCheckBox("Female", true);
 74.       add(male, gbc, 0, 1, 1, 1);
 75.       add(female, gbc, 1, 1, 1, 1);
 76.
 77.       add(new JLabel("Hobbies"), gbc, 0, 2, 1, 1);
 78.       String[] choices = { "Gardening", "Beauty",
 79.          "Computers", "Household", "Sports" };
 80.       gbc.fill = GridBagConstraints.BOTH;
 81.       hobbies = new JComboBox(choices);
 82.       add(hobbies, gbc, 1, 2, 1, 1);
 83.
 84.       gbc.fill = GridBagConstraints.NONE;
 85.       JButton submitButton = new JButton("Submit");
 86.       add(submitButton, gbc, 0, 3, 2, 1);
 87.       submitButton.addActionListener(new
 88.          ActionListener()
 89.          {
 90.             public void actionPerformed(ActionEvent evt)
 91.             {
 92.                callWarehouse();
 93.             }
 94.          });
 95.
 96.       gbc.weighty = 100;
 97.       gbc.fill = GridBagConstraints.BOTH;
 98.       result = new JTextArea(4, 40);
 99.       result.setEditable(false);
100.       add(result, gbc, 0, 4, 2, 1);
101.    }
102.
103.    /**
104.       Add a component to this frame.
105.       @param c the component to add
106.       @param gbc the grid bag constraints
107.       @param x the grid bax column
108.       @param y the grid bag row
109.       @param w the number of grid bag columns spanned
110.       @param h the number of grid bag rows spanned
111.    */
112.    private void add(Component c, GridBagConstraints gbc,
113.       int x, int y, int w, int h)
114.    {  gbc.gridx = x;
115.       gbc.gridy = y;
116.       gbc.gridwidth = w;
117.       gbc.gridheight = h;
118.       getContentPane().add(c, gbc);
119.    }
120.
121.    /**
122.       Call the remote warehouse to find matching products.
123.    */
124.    private void callWarehouse()
125.    {
126.       try
127.       {
128.          Customer c = new Customer(Integer.parseInt(age.getText()),
129.             (male.isSelected() ? Product.MALE : 0)
130.             + (female.isSelected() ? Product.FEMALE : 0),
131.             new String[] { (String)hobbies.getSelectedItem() });
132.          ArrayList recommendations = centralWarehouse.find(c);
133.          result.setText(c + "\n");
134.          for (int i = 0; i < recommendations.size(); i++)
135.          {
136.             Product p = (Product)recommendations.get(i);
137.             String t = p.getDescription() + "\n";
138.             result.append(t);
139.          }
140.       }
141.       catch(Exception e)
142.       {
143.          result.setText("Exception: " + e);
144.       }
145.    }
146.
147.    private static final int WIDTH = 300;
148.    private static final int HEIGHT = 300;
149.
150.    private Warehouse centralWarehouse;
151.    private JTextField age;
152.    private JCheckBox male;
153.    private JCheckBox female;
154.    private JComboBox hobbies;
155.    private JTextArea result;
156. }

Passing Remote Objects

Passing remote objects from the server to the client is simple. The client receives a stub object, then saves it in an object variable whose type is the same as the remote interface. The client can now access the actual object on the server through the variable. The client can copy this variable in its own local machine—all those copies are simply references to the same stub. It is important to note that only the remote interfaces can be accessed through the stub. A remote interface is any interface extending Remote. All local methods are inaccessible through the stub. (A local method is any method that is not defined in a remote interface.) Local methods can run only on the virtual machine containing the actual object.

Next, stubs are generated only from classes that implement a remote interface, and only the methods specified in the interfaces are provided in the stub classes. If a subclass doesn't implement a remote interface but a superclass does, and an object of the subclass is passed to a remote method, only the superclass methods are accessible. To understand this better, consider the following example. We derive a class BookImpl from ProductImpl.

class BookImpl extends ProductImpl
{
   public BookImpl(String title, String theISBN,
      int sex, int age1, int age2, String hobby)
   {
      super(title + " Book", sex, age1, age2, hobby);
      ISBN = theISBN;
   }
   public String getStockCode() { return ISBN; }
   private String ISBN;
}

Now, suppose we pass a book object to a remote method, either as a parameter or as a return value. The recipient obtains a stub object. But that stub is not a book stub. Instead, it is a stub to the superclass ProductImpl since only that class implements a remote interface (see Figure 5-8). Thus, in this case, the getStockCode method isn't available remotely.

Figure 5-8. Only the ProductImpl methods are remote

graphics/05fig08.gif

A remote class can implement multiple interfaces. For example, the BookImpl class can implement a second interface in addition to Product. Here, we define a remote interface StockUnit and have the BookImpl class implement it.

interface StockUnit extends Remote
{
   public String getStockCode() throws RemoteException;
}

class BookImpl extends ProductImpl implements StockUnit
{
   public BookImpl(String title, String theISBN,
      int sex, int age1, int age2, String hobby)
      throws RemoteException
   {
      super(title + " Book", sex, age1, age2, hobby);
         ISBN = theISBN;
   }

   public String getStockCode() throws RemoteException
   {
      return ISBN;
   }

   private String ISBN;
}

Figure 5-9 shows the inheritance diagram.

Figure 5-9. BookImpl has additional remote methods

graphics/05fig09.gif

Now, when a book object is passed to a remote method, the recipient obtains a stub that has access to the remote methods in both the Product and the StockUnit class. In fact, you can use the instanceof operator to find out whether a particular remote object implements an interface. Here is a typical situation where you will use this feature. Suppose you receive a remote object through a variable of type Product.

ArrayList result = centralWarehouse.find(c);
for (int i = 0; i < result.size(); i++)
{
   Product p = (Product)result.elementAt(i);
   . . .
}

Now, the remote object may or may not be a book. We'd like to use instanceof to find out whether it is or not. But we can't test

if (p instanceof BookImpl) // wrong
{  
   BookImpl b = (BookImpl)p;
   . . .
}

The object p refers to a stub object, and BookImpl is the class of the server object. We could cast the stub object to a BookImpl_Stub,

if (p instanceof BookImpl_Stub)
{
   BookImpl_Stub b = (BookImpl_Stub)p; // not useful
   . . .
}

but that would not do us much good. The stubs are generated mechanically by the rmic program for internal use by the RMI mechanism, and clients should not have to think about them. Instead, we cast to the second interface:

if (p instanceof StockUnit)
{
   StockUnit s = (StockUnit)p;
   String c = s.getStockCode();
   . . .
}

This code tests whether the stub object to which p refers implements the StockUnit interface. If so, it calls the getStockCode remote method of that interface.

To summarize:

Using Remote Objects in Sets

As we saw in Chapter 2, objects inserted in sets must override the equals method. In the case of a hash set or hash table, the hashCode method must be defined as well. However, there is a problem when trying to compare remote objects. To find out if two remote objects have the same contents, the call to equals would need to contact the servers containing the objects and compare their contents. And that call could fail. But the equals method in the class Object is not declared to throw a RemoteException, whereas all methods in a remote interface must throw that exception. Since a subclass method cannot throw more exceptions than the superclass method it replaces, you cannot define an equals method in a remote interface. The same holds for hashCode.

Instead, you must rely on the redefinitions of the equals and hashCode methods in the RemoteObject class that is the superclass for all stub and server objects. These methods do not look at the object contents, just at the location of the server objects. The equals method of the RemoteObject class deems two stubs equal if they refer to the same server object. Two stubs that refer to different server objects are never equal, even if those objects have identical contents. Similarly, the hash code is computed only from the object identifier. Stubs that refer to different server objects will likely have different hash codes, even if the server objects have identical contents.

This limitation refers only to stubs. You can redefine equals or hashCode for the server object classes. Those methods are called when you are inserting server objects in a collection on the server, but they are never called when you are comparing or hashing stubs. To clarify the difference between client and server behavior, look at the inheritance diagram in Figure 5-10.

Figure 5-10. Inheritance of equals and hashCode methods

graphics/05fig10.gif

The RemoteObject class is the base for both stub and server classes. On the stub side, you cannot override the equals and hashCode methods because the stubs are mechanically generated. On the server side, you can override the methods for the implementation classes, but they are only used locally on the server. If you do override these methods, implementation and stub objects are no longer considered identical.

To summarize: You can use stub objects in hash tables, but you must remember that equality testing and hashing do not take the contents of the remote objects into account.

Cloning Remote Objects

Stubs do not have a clone method, so you cannot clone a remote object by invoking clone on the stub. The reason is again somewhat technical. If clone were to make a remote call to tell the server to clone the implementation object, then the clone method would need to throw a RemoteException. But the clone method in the Object superclass promised never to throw any exception except CloneNotSupportedException. That is the same limitation that you encountered in the previous section, when you saw that equals and hashCode don't look up the remote object value at all but just compare stub references. But it makes no sense for clone to make another clone of a stub—if you wanted to have another reference to the remote object, you could just copy the stub variable. Therefore, clone is simply not defined for stubs.

If you want to clone a remote object, you must write another method, say, remoteClone. Place it into the interface that defines the remote object services. Of course, that method may throw a RemoteException. In the implementation class, simply define remoteClone to call clone and return the cloned implementation object.

interface Product extends Remote
{
   public Object remoteClone() 
      throws RemoteException, CloneNotSupportedException;
   . . .
}

class ProductImpl extends UnicastRemoteObject
   implements Product
{
   public Object remoteClone()
      throws CloneNotSupportedException
   { return clone(); }
   . . .
}

Inappropriate Remote Parameters

Suppose we enhance our shopping application by having the application show a picture of each gift. Can we simply add the remote method

void paint(Graphics g) throws RemoteException

to the Product interface? Unfortunately, this code cannot work, and it is important to understand why. The problem is that the Graphics class does not implement remote interfaces. Therefore, a copy of an object of type Graphics would need to be passed to the remote object, and you can't do this. Why? Well, Graphics is an abstract class, and Graphics objects are returned via a call to the getGraphics method of the Component class. This call, in turn, can happen only when you have some subclass that implements a graphics context on a particular platform. Those objects, in turn, need to interact with the native graphics code, and to do so, they must store pointers to the memory blocks that are needed by the native graphics methods. The Java programming language, of course, has no pointers, so this information is stored as integers in the graphics object and is only cast back to pointers in the native peer methods. Now, first of all, the target machine may be a different platform. For example, if the client runs Windows and the server runs X11, then the server does not have the native methods available to render Windows graphics. But even if the server and the client have the same graphics system, the pointer values would not be valid on the server. Therefore, it makes no sense to copy a graphics object. For that reason, the Graphics class is not serializable and so cannot be sent via RMI.

Instead, if the server wants to send an image to the client, it has to come up with some other mechanism for transporting the data across the network. As it turns out, this data transport is actually difficult to do for images. The Image class is just as device-dependent as the Graphics class. We could send the image data as a sequence of bytes in JPEG format. Another alternative is to send an array of integers representing the pixels. In the next section, we show how to solve this problem in a more mundane way: by sending a URL to the client and using a method of the Applet class that can read an image from a URL.

Using RMI with Applets

There are a number of special concerns when running RMI with applets. Applets have their own security manager since they run inside a browser. Thus, we do not use the RMISecurityManager on the client side.

We must take care where to place the stub and server files. Consider a browser that opens a web page with an applet tag. The browser loads the class file referenced in that tag and all other class files as they are needed during execution. The class files are loaded from the same host that contains the web page. Because of applet security restrictions, the applet can make network connections only to its originating host. Therefore, the server objects must reside on the same host as the web page. That is, the same server must store

Here is a sample applet that further extends our shopping program. Just like the preceding application, the applet gets the customer information and then selects matching products. However, this applet sends images of the recommended items. As we mentioned previously, it is not easy to send an image from the server to the client because images are stored in a format that depends on the local graphics system. Instead, the server simply sends the client a string with the image file name, and we use the getImage method of the Applet class to obtain the image (see Figure 5-11).

Figure 5-11. The warehouse applet

graphics/05fig11.gif

Here is how you must distribute the code for this kind of situation:

The applet looks for the RMI registry on the same host that contains the applet. To find out its host, it uses the getCodeBase and getHost methods:

String url = "rmi://" + getCodeBase().getHost()
   + "/central\u-4001warehouse";
centralWarehouse = (Warehouse)Naming.lookup(url);

Example 5-14 shows the code for the applet. Note that the applet does not install a security manager. Example 5-15 shows the applet HTML page. The product and warehouse implementations have been changed slightly to add the image file name field. See the companion code for these straightforward modifications.

Example 5-14 WarehouseApplet.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.io.*;
  4. import java.rmi.*;
  5. import java.rmi.server.*;
  6. import java.util.*;
  7. import javax.swing.*;
  8.
  9. /**
 10.    The warehouse client applet. 
 11. */
 12. public class WarehouseApplet extends JApplet
 13. {
 14.    public void init()
 15.    {
 16.       initUI();
 17.
 18.       try
 19.       {
 20.          String warehouseName = getParameter("warehouse.name");
 21.          if (warehouseName == null)
 22.             warehouseName = "central_warehouse";
 23.          String url = "rmi://" + getCodeBase().getHost()
 24.             + "/" + warehouseName;
 25.          centralWarehouse = (Warehouse)Naming.lookup(url);
 26.       }
 27.       catch(Exception e)
 28.       {
 29.          showStatus("Error: Can't connect to warehouse. " + e);
 30.       }
 31.    }
 32.
 33.    /**
 34.       Initializes the user interface.
 35.    */
 36.    private void initUI()
 37.    {
 38.       getContentPane().setLayout(new GridBagLayout());
 39.
 40.       GridBagConstraints gbc = new GridBagConstraints();
 41.       gbc.fill = GridBagConstraints.HORIZONTAL;
 42.       gbc.weightx = 100;
 43.       gbc.weighty = 0;
 44.
 45.       add(new JLabel("Age:"), gbc, 0, 0, 1, 1);
 46.       age = new JTextField(4);
 47.       age.setText("20");
 48.       add(age, gbc, 1, 0, 1, 1);
 49.
 50.       male = new JCheckBox("Male", true);
 51.       female = new JCheckBox("Female", true);
 52.       add(male, gbc, 0, 1, 1, 1);
 53.       add(female, gbc, 1, 1, 1, 1);
 54.
 55.       add(new JLabel("Hobbies"), gbc, 0, 2, 1, 1);
 56.       String[] choices = { "Gardening", "Beauty",
 57.          "Computers", "Household", "Sports" };
 58.       gbc.fill = GridBagConstraints.BOTH;
 59.       hobbies = new JComboBox(choices);
 60.       add(hobbies, gbc, 1, 2, 1, 1);
 61.
 62.       gbc.fill = GridBagConstraints.NONE;
 63.       JButton submitButton = new JButton("Submit");
 64.       add(submitButton, gbc, 0, 3, 2, 1);
 65.       submitButton.addActionListener(new
 66.          ActionListener()
 67.          {
 68.             public void actionPerformed(ActionEvent evt)
 69.             {
 70.                callWarehouse();
 71.             }
 72.          });
 73.
 74.       gbc.weighty = 100;
 75.       gbc.fill = GridBagConstraints.BOTH;
 76.       result = new JTextArea(4, 40);
 77.       result.setEditable(false);
 78.       add(result, gbc, 0, 4, 2, 1);
 79.
 80.       imagePanel = new JPanel();
 81.       imagePanel.setMinimumSize(new Dimension(0, 60));
 82.       add(imagePanel, gbc, 0, 5, 2, 1);
 83.    }
 84.
 85.    /**
 86.       Add a component to this frame.
 87.       @param c the component to add
 88.       @param gbc the grid bag constraints
 89.       @param x the grid bax column
 90.       @param y the grid bag row
 91.       @param w the number of grid bag columns spanned
 92.       @param h the number of grid bag rows spanned
 93.    */
 94.    private void add(Component c, GridBagConstraints gbc,
 95.       int x, int y, int w, int h)
 96.    {  gbc.gridx = x;
 97.       gbc.gridy = y;
 98.       gbc.gridwidth = w;
 99.       gbc.gridheight = h;
100.       getContentPane().add(c, gbc);
101.    }
102.
103.    /**
104.       Call the remote warehouse to find matching products.
105.    */
106.    private void callWarehouse()
107.    {
108.       try
109.       {
110.          Customer c = new Customer(Integer.parseInt(age.getText()),
111.             (male.isSelected() ? Product.MALE : 0)
112.             + (female.isSelected() ? Product.FEMALE : 0),
113.             new String[] { (String)hobbies.getSelectedItem() });
114.          ArrayList recommendations = centralWarehouse.find(c);
115.          result.setText(c + "\n");
116.          imagePanel.removeAll();
117.          for (int i = 0; i < recommendations.size(); i++)
118.          {
119.             Product p = (Product)recommendations.get(i);
120.             String t = p.getDescription() + "\n";
121.             result.append(t);
122.             Image productImage
123.                = getImage(getCodeBase(), p.getImageFile());
124.             imagePanel.add(new JLabel(new ImageIcon(productImage)));
125.          }
126.       }
127.       catch(Exception e)
128.       {
129.          result.setText("Exception: " + e);
130.       }
131.    }
132.
133.    private static final int WIDTH = 300;
134.    private static final int HEIGHT = 300;
135.
136.    private Warehouse centralWarehouse;
137.    private JTextField age;
138.    private JCheckBox male;
139.    private JCheckBox female;
140.    private JComboBox hobbies;
141.    private JTextArea result;
142.    private JPanel imagePanel;
143. }
Example 5-15 WarehouseApplet.html
1. <applet code="WarehouseApplet.class" width="600" height="400">
2.    <param name="warehouse.name" value="central_warehouse"/>
3. </applet>

Server Object Activation

In the preceding sample programs, we used a server program to instantiate and register objects so that clients could make remote calls on them. However, in some cases, it may be wasteful to instantiate lots of server objects and have them wait for connections, whether or not client objects use them. The activation mechanism lets you delay the object construction, so that a server object is only constructed when at least one client invokes a remote method on it.

To take advantage of activation, the client code is completely unchanged. The client simply requests a remote reference and makes calls through it.

However, the server program is replaced by an activation program that constructs activation descriptors of the objects that are to be constructed at a later time, and binds receivers for remote method calls with the naming service. When a call is made for the first time, the information in the activation descriptor is used to construct the object.

A server object that is used in this way should extend the Activatable class and, of course, implement one or more remote interfaces. For example,

class ProductImpl 
   extends Activatable 
   implements Product 
{
   . . . 
}

Because the object construction is delayed until a later point in time, it must happen in a standardized form. Therefore, you must provide a constructor that takes two parameters:

If you need multiple construction parameters, you must package them up in a single object. You can always use an Object[] array or an ArrayList. As you will see momentarily, you will place a serialized (or marshalled) copy of the construction information inside the activation descriptor. Your server object constructor should use the get method of the MarshalledObject class to deserialize the construction information.

In the case of the ProductImpl class, this is quite simple—there is only one piece of information necessary for construction, namely the product name. That information can be wrapped into a MarshalledObject and unwrapped in the constructor:

public ProductImpl(ActivationID id, MarshalledObject data)
{
   super(id, 0);
   String n = (String)data.get();
   name = n;
   System.out.println("Constructed " + name);
}

By passing 0 as the second parameter of the superclass constructor, we indicate that the RMI library should assign a suitable port number to the listener port.

This constructor prints a message so that you can see that the product objects are activated on demand.

NOTE

graphics/note.gif
 

Your server objects don't actually have to extend the Activatable class. If they don't, then place the static method call

Activatable.exportObject(this, id, 0)

in the constructor of the server class.

Now let us turn to the activation program. First, you need to define an activation group. An activation group describes common parameters for launching the virtual machine that contains the server objects. The most important parameter is the security policy.

As with our other server objects, we will not do security checks. (Presumably they come from a trusted source.) However, the virtual machine in which the activated objects run has a security manager installed. To enable all permissions, supply a file server.policy with the following contents:

grant
{
   permission java.security.AllPermission;
};

Construct an activation group descriptor as follows:

Properties props = new Properties();
props.put("java.security.policy", "/server/server.policy");
ActivationGroupDesc group = new ActivationGroupDesc(prop, null);

The second parameter is used to describe special command options; we will not need any for this example, so we pass a null reference.

Next, you create a group ID with the call

ActivationGroupID id 
   = ActivationGroup.getSystem().registerGroup(group);

Now you are ready to construct the activation descriptors. For each object that should be constructed on demand, you need

For example,

MarshalledObject param 
   = new MarshalledObject("Blackwell Toaster");
ActivationDesc desc = new ActivationDesc(id, "ProductImpl",
   "http://myserver.com/download/", param); 

Pass the descriptor to the static Activatable.register method. It returns an object of some class that implements the remote interfaces of the implementation class. You can bind that object with the naming service:

Product p = (Product)Activatable.register(desc);
Naming.rebind("toaster", p);

Unlike the server programs of the preceding examples, the activation program exits after registering and binding the activation receivers. The server objects are only constructed when the first remote method call occurs.

Examples 5-16 and 5-17 show the code for the activatable product implementation and the activation program. The product interface and the client program are unchanged.

To launch this program, follow these steps:

  1. Compile all source files.

  2. Run rmic to generate a stub for the ProductImpl class:

    rmic -v1.2 ProductImpl
    
  3. Start the RMI registry.

  4. Start the RMI activation daemon.

    rmid -J-Djava.security.policy=rmid.policy &
    

    or

    start rmid -J-Djava.security.policy=rmid.policy
    

    The rmid program listens to activation requests and activates objects in a separate virtual machine. To launch a virtual machine, the rmid program needs certain permissions. These are specified in a policy file (see Example 5-18). The -J option is used to pass an option to the virtual machine running the activation daemon.

  5. Run the activation program. In this setup, we assume that you start the program in the directory that contains the class files and the server policy file.

    java ProductActivator
    

    The program will exit after the activation receivers have been registered with the naming service.

  6. Run the client program

    java -Djava.security.policy=client.policy ProductClient
    

    The client will print the familiar product descriptions. When you run the client for the first time, you will also see the constructor messages in the server shell window.

Example 5-16 ProductImpl.java
 1. import java.io.*;
 2. import java.rmi.*;
 3. import java.rmi.activation.*;
 4.
 5. /**
 6.    This is the implementation class for the remote product
 7.    objects.
 8. */
 9. public class ProductImpl
10.    extends Activatable
11.    implements Product
12. {
13.    /**
14.       Constructs a product implementation
15.       @param id the activation id
16.       @param data the marshalled construction parameter (containing the
17.       product name)
18.    */
19.    public ProductImpl(ActivationID id, MarshalledObject data) 
20.       throws RemoteException, IOException, ClassNotFoundException
21.    {
22.       super(id, 0);
23.       String n = (String)data.get();
24.       name = n;
25.       System.out.println("Constructed " + name);
26.    }
27.
28.    public String getDescription() throws RemoteException
29.    {
30.       return "I am a " + name + ". Buy me!";
31.    }
32.
33.    private String name;
34. }
Example 5-17 ProductActivator.java
 1. import java.io.*;
 2. import java.net.*;
 3. import java.rmi.*;
 4. //import java.rmi.server.*;
 5. import java.rmi.activation.*;
 6. import java.util.*;
 7.
 8. /**
 9.    This server program activates two remote objects and
10.    registers them with the naming service.
11. */
12. public class ProductActivator
13. {
14.    public static void main(String args[])
15.    {
16.       try
17.       {
18.          System.out.println
19.             ("Constructing activation descriptors...");
20.
21.          Properties props = new Properties();
22.          // use the server.policy file in the current directory
23.          props.put("java.security.policy", 
24.             new File("server.policy").getCanonicalPath());
25.         ActivationGroupDesc group = new ActivationGroupDesc(props, null);
26.           ActivationGroupID id 
27.              = ActivationGroup.getSystem().registerGroup(group);
28.           MarshalledObject p1param 
29.              = new MarshalledObject("Blackwell Toaster");
30.           MarshalledObject p2param
31.              = new MarshalledObject("ZapXpress Microwave Oven");
32.
33.           String classDir = ".";
34.           // turn the class directory into a file URL
35.         // for this demo we assume that the classes are in the current dir
36.           String classURL 
37.             = new File(classDir).getCanonicalFile().toURL().toString();
38.
39.           ActivationDesc desc1 = new ActivationDesc
40.               (id, "ProductImpl", classURL, p1param);
41.           ActivationDesc desc2 = new ActivationDesc
42.               (id, "ProductImpl", classURL, p2param);
43.
44.           Product p1 = (Product)Activatable.register(desc1);
45.           Product p2 = (Product)Activatable.register(desc2);
46.
47.           System.out.println
48.              ("Binding activable implementations to registry...");
49.
50.           Naming.rebind("toaster", p1);
51.           Naming.rebind("microwave", p2);
52.
53.           System.out.println
54.              ("Exiting...");
55.       }
56.       catch(Exception e)
57.       {
58.          e.printStackTrace();
59.       }
60.    }
61. }
Example 5-18 rmid.policy
1. grant
2. {
3.    permission com.sun.rmi.rmid.ExecPermission 
4.       "${java.home}${/}bin${/}java";
5.    permission com.sun.rmi.rmid.ExecOptionPermission
6.       "-Djava.security.policy=*";
7. };
Example 5-19 server.policy
1. grant 
2. {
3.    permission java.security.AllPermission;
4. };
Example 5-20 client.policy
1. grant 
2. {
3.    permission java.net.SocketPermission 
4.       "*:1024-65535", "connect,accept";
5.    permission java.net.SocketPermission 
6.       "localhost:80", "connect";
7. };

java.rmi.activation.Activatable

graphics/api.gif
 

java.rmi.MarshalledObject

graphics/api.gif
 

java.rmi.activation.ActivationGroupDesc

graphics/api.gif
 

java.rmi.activation.ActivatationGroup

graphics/api.gif
 

java.rmi.activation.ActivationSystem

graphics/api.gif
 

java.rmi.activation.ActivatationDesc

graphics/api.gif
 

Java IDL and CORBA

Unlike RMI, CORBA lets you make calls between Java objects and objects written in other languages. CORBA depends on having an Object Request Broker (ORB) available on both client and server. You can think of an ORB as a kind of universal translator for interobject CORBA communication. The CORBA 2 specification defines more than a dozen "services" that the ORB can use for various kinds of housekeeping tasks. These range from a "startup service" to get the process going, to a "life cycle service" that you use to create, copy, move, or destroy objects to a "naming service" that allows you to search for objects if you know their name.

The Java 2 platform contains an implementation of a CORBA 2 compliant ORB. Thus, all applications and applets that you deploy for the Java 2 platform have the ability to connect to remote CORBA objects.

NOTE

graphics/note.gif
 

Sun refers to the CORBA support in the Java 2 platform as "Java IDL." That term is really a misnomer. IDL refers to the interface definition language, a language for describing class interfaces. The important aspect of the technology is connectivity with CORBA, not just support for IDL.

Here are the steps for implementing CORBA objects:

  1. Write the interface that specifies how the object works, using IDL, the interface definition language for defining CORBA interfaces. IDL is a special language to specify interfaces in a language-neutral form.

  2. Using the IDL compiler(s) for the target language(s), generate the needed stub and helper classes.

  3. Add the implementation code for the server objects, using the language of your choice. (The skeleton created by the IDL compiler is only glue code. You still need to provide the actual implementation code for the server methods.) Compile the implementation code.

  4. Write a server program that creates and registers the server objects. The most convenient method for registration is to use the CORBA naming service, a service that is similar to the rmiregistry.

  5. Write a client program that locates the server objects and invokes services on them.

  6. Start the naming service and the server program on the server and the client program on the client.

These steps are quite similar to the steps that you use to build distributed applications with RMI. There are two important differences:

In the following sections, you will see how to use IDL to define CORBA interfaces, and how to connect clients implemented in the Java programming language with C++ servers and C++ clients with servers implemented in the Java programming language.

However, CORBA is a complex subject, and we only give you a couple of basic examples to show you how to get started. For more information, we recommend Client/Server Programming with Java and CORBA by Robert Orfali and Dan Harkey [John Wiley & Sons 1998]. More advanced, and definitely not for the faint of heart, is Advanced CORBA Programming with C++ by Michi Henning and Steve Vinoski [Addison-Wesley 1999].

The Interface Definition Language

To introduce the IDL syntax, let us quickly run through the same example that we used for RMI. In RMI, you started out with an interface in the Java programming language. With CORBA, the starting point is an interface in IDL syntax:

interface Product
{
   string getDescription();
};

There are a few subtle differences between IDL and the Java programming language. In IDL, the interface definition ends with a semicolon. Note that string is written in lower case. In fact, the string class refers to the CORBA notion of a string, which is different from a Java string. In the Java programming language, strings contain 16-bit Unicode characters. In CORBA, strings only contain 8-bit characters. If you send the 16-bit string through the ORB and the string has characters with nonzero high byte, an exception is thrown. This kind of type mismatch problem is the price you pay for interoperability between programming languages.

NOTE

graphics/note.gif
 

CORBA also has wchar and wstring types for "wide" characters. However, there is no guarantee that wide character strings use the Unicode encoding.

The "IDL to Java" compiler (Java IDL compiler) translates IDL definitions to definitions for interfaces in the Java programming language. For example, suppose you place the IDL Product definition into a file Product.idl and run

idlj Product.idl

The result is a file ProductOperations.java with the following contents

interface ProductOperations
{
   String getDescription();
}

and a file Product.java that defines an interface

public interface Product extends 
   ProductOperations, 
   org.omg.CORBA.Object, 
   org.omg.CORBA.portable.IDLEntity 
{
}

NOTE

graphics/note.gif
 

In SDK1.2, the idltojava program is used to translate IDL files.

The IDL compiler also generates a number of other source files—the stub class for communicating with the ORB and three helper classes that you will encounter later in this section and the next.

NOTE

graphics/note.gif
 

You cannot do any programming in IDL. IDL can only express interfaces. The CORBA objects that IDL describes must still be implemented, for example, in C++ or the Java programming language.

The rules that govern the translation from IDL to the Java programming language are collectively called the Java programming language binding. Language bindings are standardized by the OMG; all CORBA vendors are required to use the same rules for mapping IDL constructs to a particular programming language.

We will not discuss all aspects of IDL or the Java programming language binding—see the CORBA documentation at the web site of the Object Management Group (www.omg.org) for a full description. However, there are a number of important concepts that every IDL user needs to know.

When defining a method, you have more choices for parameter passing than the Java programming language offers. Every parameter can be declared as in, out, or inout. An in parameter is simply passed to the method—this is the same parameter-passing mechanism as in the Java programming language. However, the Java programming language has no analog to an out parameter. A method stores a value in each out parameter before it returns. The caller can retrieve the values stored in out parameters.

For example, a find method might store the product object that it has found:

interface Warehouse
{
   boolean locate(in String descr, out Product p);
   . . .
};

If the parameter is declared as out only, then the method should not expect the parameter to be initialized. However, if it is declared as inout, then the caller needs to supply a value for the method, and the method can change that value so that the caller can retrieve the changed value. In the Java programming language, these parameters are simulated with special holder classes that are generated by the Java IDL compiler.

The IDL compiler generates a class with suffix Holder for every interface. For example, when compiling the Product interface, it automatically generates a ProductHolder class. Every holder class has a public instance variable called value.

When a method has an out parameter, the IDL compiler changes the method signature to use a holder, for example

interface Warehouse
{
   boolean locate(String descr, ProductHolder p);
   . . .
};

When calling the method, you need to pass in a holder object. After the method returns, you retrieve the value of the out parameter from the holder object. Here is how you call the locate method.

Warehouse w = . . .;
String descr = . . .;
Product p;
ProductHolder pHolder = new ProductHolder();
if (w.locate(descr, pHolder))
   p = pHolder.value;

There are predefined holder classes for fundamental types (such as IntHolder, DoubleHolder and so on).

NOTE

graphics/note.gif
 

IDL does not support overloaded methods. You need to come up with a different name for each method.

In IDL, you use the sequence construct to define arrays of variable size. You must first define a type before you can declare sequence parameters or return values. For example, here is the definition of a "sequence of products" type.

typedef sequence<Product> ProductSeq;

Then you can use that type in method declarations:

interface Warehouse
{
   ProductSeq find(in Customer c);
   . . .
};

In the Java programming language, sequences correspond to arrays. For example, the find method is mapped to

Product[] find(Customer c)

If a method can throw an exception, you first define the exception type and then use a raises declaration. In the following example, the find method can raise a BadCustomer exception.

interface Warehouse
{
   exception BadCustomer { string reason; };
   ProductSeq find(in Customer c) raises BadCustomer;
   . . .
};

The IDL compiler translates the exception type into a class.

final public class BadCustomer 
   extends org.omg.CORBA.UserException 
{
   public BadCustomer() {}
   public BadCustomer(String __reason) { reason = __reason; }
   public String reason; 
}

If you catch such an exception, you can look into its public instance variables.

The raises specifier becomes a throws specifier of the Java method

ProductSeq find(Customer c) throws BadCustomer

Interfaces can contain constants, for example,

interface Warehouse
{
   const int SOLD_OUT = 404;
   . . .
};

Interfaces can also contain attributes. Attributes look like instance variables, but they are actually shorthand for a pair of accessor and mutator methods. For example, here is a Book interface with an isbn attribute:

interface Book
{
   attribute string isbn;
   . . .
};

The equivalent in the Java programming language is a pair of methods, both with the name isbn:

String isbn() // accessor
void isbn(String __isbn) // mutator

If the attribute is declared as readonly, then no mutator method is generated.

You cannot specify variables in CORBA interfaces—the data representation for objects is part of the implementation strategy, and IDL does not address implementation at all.

CORBA supports interface inheritance, for example,

interface Book : Product { /* . . . */ };

You use the colon (:) to denote inheritance. An interface can inherit multiple interfaces.

In IDL, you can group definitions of interfaces, types, constants, and exceptions into modules.

module corejava
{
   interface Product
   {
      . . . 
   };

   interface Warehouse
   {
      . . .
   };
};

Modules are translated to packages in the Java programming language.

Once you have the IDL file, you run the IDL compiler that your ORB vendor supplies to get stubs and helper classes for your target language (such as the Java programming language or the C++ language).

For example, to convert IDL files to the Java programming language, you run the idltojava program. Supply the name of the IDL file on the command line:

idlj Product.idl

The program creates five source files:

The same IDL file can be compiled to C++. We will use a freely available ORB called omniORB for our examples. The omniORB package contains an IDL-to-C++ compiler called omniidl. To generate C++ stubs, invoke it as

omniidl -bcxx Product.idl

You get two C++ files:

NOTE

graphics/note.gif
 

While the language binding is standardized, it is up to each vendor to decide how to generate and package the code that realizes the binding. IDL-to-C++ compilers of other vendors will generate a different set of files.

A CORBA Example

In our first example, we show you how to call a C++ server object from a client implemented in the Java programming language, using the CORBA support that is built into the Java 2 platform. On the server side, we will use omniORB, a freely available ORB that works with the Java 2 platform. You can download omniORB from http://www.uk.research.att.com/omniORB/index.html.

NOTE

graphics/note.gif
 

The omniORB product is free, but on Windows, it requires the Microsoft C++ compiler. On Linux, you can use omniORB with the GNU C++ compiler.

NOTE

graphics/note.gif
 

In principle, of course, you can use any CORBA 2 compliant ORB on the server. However, you will need to make some changes to the C++ code if you use a different ORB. Also, if our experience is any guide, you may run into bootstrapping issues. At the end of this section, we give you a couple of tips on connecting to other ORBs.

Our example C++ server object simply reports the value of an environment variable on the server. The interface is

interface Env
{
   string getenv(in string name);
};

For example, the following program fragment in the Java programming language obtains the value of the PATH environment variable of the process in which the server object runs.

Env env = . . .;
String value = env.getenv("PATH")

The C++ implementation code for this interface is straightforward. We simply call the getenv method in the standard C library.

class EnvImpl 
   : public POA_Env, public PortableServer::RefCountServantBase
{
public:
   virtual char* getenv(const char *name)
   {
      char* value = std::getenv(name);
      return CORBA::string_dup(value);
   }
};

You don't need to understand the C++ code to follow this section—just treat it as a bit of legacy code that you want to encapsulate in a CORBA object so that you can call it from programs written in the Java programming language.

On the server side, you now need to write a C++ program that does the following:

  1. Starts the ORB;

  2. Creates an object of the EnvImpl class and registers it with the ORB;

  3. Uses the name server to bind the object to a name;

  4. Waits for invocations from a client.

You can find that program in Example 5-22 at the end of this section. We will not discuss the C++ code in detail. If you are interested, consult the omniORB documentation for more information. The documentation contains a good tutorial that explains each step in detail.

Let us now turn to the client code. You already saw how to invoke a method on the server object once you have a reference to the remote object. However, to get to that reference, you have to go through a different set of mumbo-jumbo than in RMI.

First, you initialize the ORB. The ORB is simply a code library that knows how to talk to other ORBs and how to marshal and unmarshal parameters.

ORB orb = ORB.init(args, null);

Next, you need to locate the naming service that helps you locate other objects. However, in CORBA, the naming service is just another CORBA object. To call the naming service, you first need to locate it. In the days of CORBA 1, this was a major problem, since there was no standard way of getting a reference to it. However, a CORBA 2 ORB lets you locate certain standard services by name. The call

String[] services = orb.list_initial_services();

lists the names of the standard services that the ORB can connect to. The naming service has the standard name NameService. Most ORBs have additional initial services, such as the RootPOA service that is used to access the root Portable Object Adaptor.

To obtain an object reference to the service, you use the resolve_initial_references method. It returns a generic CORBA object, an instance of the class org.omg.corba.Object. You need to use the full package prefix; if you just use Object, then the compiler assumes that you mean java.lang.Object.

org.omg.CORBA.Object object
   = orb.resolve_initial_references("NameService");

Next, you need to convert this reference into a NamingContext reference so that you can invoke the methods of the NamingContext interface. In RMI, you would simply cast the reference to a different type. However, in CORBA, you cannot simply cast references.

NamingContext namingContext 
   = (NamingContext)object; // ERROR

Instead, you have to use the narrow method of the helper class of the target interface.

NamingContext namingContext 
   = NamingContextHelper.narrow(object);

CAUTION

graphics/caution.gif
 

Casting a CORBA object reference to a subtype will sometimes succeed. Many org.omg.CORBA.Object references already point to objects that implement the appropriate interface. But an object reference can also hold a delegate to another object that actually implements the interface. Since you don't have any way of knowing how the stub objects were generated, you should always use the narrow method to convert a CORBA object reference to a subtype.

Now that you have the naming context, you can use it to locate the object that the server placed into it. The naming context associates names with server objects. Names are nested sequences of name components. You can use the nesting levels to organize hierarchies of names, much like you use directories in a file system.

A name component consists of an ID and a kind. The ID is a name for the component that is unique among all names with the same parent component. The kind is some indication of the type of the component. These kinds are not standardized; we use "Context" for name components that have nested names, and "Object" for object names.

In our example, the server program has placed the EnvImpl object into the name expressed by the sequence

(id="corejava", kind="Context"), (id="Env", kind="Object") 

We retrieve a remote reference to it by building up an array of name components and passing it to the resolve method of the NamingContext interface.

NameComponent[] path = 
   {
      new NameComponent("corejava", "Context"),
      new NameComponent("Env", "Object") 
   };
org.omg.CORBA.Object envObj = namingContext.resolve(path);

Once again, we must narrow the resulting object reference:

Env env = EnvHelper.narrow(envObj);

Now we are ready to call the remote method:

String value = env.getenv("PATH");

You will find the complete code in Example 5-21.

This example shows the steps to follow in a typical client program:

  1. Start the ORB.

  2. Locate the naming service by retrieving an initial reference to "NameService" and narrowing it to a NamingContext reference.

  3. Locate the object whose methods you want to call by assembling its name and calling the resolve method of the NamingContext.

  4. Narrow the returned object to the correct type and invoke your methods.

To actually test this program, do the following.

  1. Compile the IDL file, using both the C++ and Java IDL compilers.

  2. Compile the C++ server program. The compilation instructions depend on the ORB. For example, with OmniORB on Linux, you use

    g++
       -o EnvServer
       -D__x86__ -D__linux__ -D__OSVERSION__=2
       -I/usr/local/omni/include
       -L/usr/local/omni/lib/i586_linux_2.0_glibc2.1/
       EnvServer.cpp EnvSK.cc 
       -lomniORB3 -ltcpwrapGK -lomnithread -lpthread
    

    To find out what you need with your particular ORB, compile one of the example programs that are supplied with your installation and make the appropriate modifications to compile your own programs.

  3. Compile the Java client program.

  4. Start the naming service on the server (for example, omniNames if you use omniORB). The naming service runs until you kill it.

  5. Start the server:

    ./EnvServer &
    

    The server also runs until you kill it.

  6. Run the client, for example

    java EnvClient -ORBInitialPort 2809
    

    The client program should report the PATH of the server process.

TIP

graphics/tip.gif
 

There are a couple of OmniORB configuration issues that you need to follow carefully. Be sure to set the LD_LIBRARY_PATH (on Unix/Linux) or the PATH (on Windows) to include the directory containing the OmniORB libraries. You also need to make a configuration file and set the OMNIORB_CONFIG environment variable. The configuration file contains the IOR (Interoperable Object Reference) of the name service. See the sidebar at the end of this section for more details on IORs, and precisely follow the steps in the OmniORB documentation.

If the server is on a remote machine, or if the initial port of the server ORB is not the same as the Java IDL default of 900, then you need to set the ORBInitialHost and ORBInitialPort properties. For example, OmniORB uses port 2809, so you need to set the initial port.

There are two methods for setting these properties. You can set the system properties

org.omg.CORBA.ORBInitialHost
org.omg.CORBA.ORBInitialPort

for example, by starting the java interpreter with the -D option. Or, you can specify the values on the command line:

java EnvClient -ORBInitialHost warthog -ORBInitialPort 2809

The command line parameters are passed to the ORB by the call

ORB orb = ORB.init(args, null);

In principle, your ORB vendor should tell you with great clarity how its bootstrap process works. In practice, we have found that vendors blithely assume that you would never dream of mixing their precious ORB with another, and they tend to be less than forthcoming with this information. If your client won't find the naming service, try forcing the initial ports for both the server and the client to the same value.

TIP

graphics/tip.gif
 

If you have trouble connecting to the naming service, print out a list of initial services that your ORB can locate.

public class ListServices
{
   public static void main(String args[]) throws Exception
   {
      ORB orb = ORB.init(args, null);
      String[] services = orb.list_initial_services();
      for (int i = 0; i < services.length; i++)
         System.out.println(services[i]);
   }
}

With some ORBs, NameService isn't among the listed services, no matter how much you tweak the configuration. Then, you should switch to Plan B and locate the server object by its Interoperable Object Reference, or IOR. See the sidebar for more information.

In this section, you saw how to connect to a server that was implemented in C++. We believe that is a particularly useful scenario. You can wrap legacy services into CORBA objects and access them from any program for the Java 2 platform, without having to deploy additional system software on the client. In the next section, you will see the opposite scenario, where the server is implemented in the Java programming language and the client in C++.

Example 5-21 EnvClient.java
 1. import org.omg.CosNaming.*;
 2. import org.omg.CORBA.*;
 3.
 4. public class EnvClient
 5. {
 6.    public static void main(String args[])
 7.    {
 8.       try
 9.       {
10.          ORB orb = ORB.init(args, null);
11.          org.omg.CORBA.Object namingContextObj
12.             = orb.resolve_initial_references("NameService");
13.          NamingContext namingContext
14.             = NamingContextHelper.narrow(namingContextObj);
15.
16.          NameComponent[] path = 
17.             {
18.                new NameComponent("corejava", "Context"),
19.                new NameComponent("Env", "Object") 
20.             };
21.          org.omg.CORBA.Object envObj 
22.             = namingContext.resolve(path);
23.          Env env = EnvHelper.narrow(envObj);
24.          System.out.println(env.getenv("PATH"));
25.       }
26.       catch(Exception e)
27.       {
28.          e.printStackTrace();
29.       }
30.    }
31. }
Example 5-22 EnvServer.cpp
  1. #include <iostream>
  2. #include <cstdlib>
  3.
  4. #include "Env.hh"
  5.
  6. using namespace std;
  7.
  8. class EnvImpl : 
  9.    public POA_Env,
 10.    public PortableServer::RefCountServantBase
 11. {
 12. public:
 13.    virtual char* getenv(const char *name);
 14. };
 15.
 16. char* EnvImpl::getenv(const char *name)
 17. {
 18.    char* value = std::getenv(name);
 19.    return CORBA::string_dup(value);
 20. }
 21.
 22. static void bindObjectToName(CORBA::ORB_ptr orb, 
 23.    const char name[], CORBA::Object_ptr objref)
 24. {
 25.    CosNaming::NamingContext_var rootContext;
 26.
 27.    try
 28.    {
 29.       // Obtain a reference to the root context of the 
 30.       // name service:
 31.       CORBA::Object_var obj;
 32.       obj = orb->resolve_initial_references("NameService");
 33.
 34.       // Narrow the reference returned.
 35.       rootContext = CosNaming::NamingContext::_narrow(obj);
 36.       if( CORBA::is_nil(rootContext) )
 37.       {
 38.          cerr << "Failed to narrow the root naming context." 
 39.             << endl;
 40.          return;
 41.       }
 42.    }
 43.    catch(CORBA::ORB::InvalidName& ex) 
 44.    {
 45.       // This should not happen!
 46.       cerr << "Service required is invalid [does not exist]." 
 47.          << endl;
 48.       return;
 49.    }
 50.
 51.    try
 52.    {
 53.       // Bind a context called "test" to the root context:
 54.
 55.       CosNaming::Name contextName;
 56.       contextName.length(1);
 57.       contextName[0].id   = (const char*) "corejava"; 
 58.       contextName[0].kind = (const char*) "Context"; 
 59.
 60.       CosNaming::NamingContext_var corejavaContext;
 61.       try
 62.       {
 63.          // Bind the context to root.
 64.          corejavaContext 
 65.             = rootContext->bind_new_context(contextName);
 66.       }
 67.       catch(CosNaming::NamingContext::AlreadyBound& ex) 
 68.       {
 69.          // If the context already exists, this exception will 
 70.          // be raised. In this case, just resolve the name and 
 71.          // assign the context to the object returned:
 72.          CORBA::Object_var obj;
 73.          obj = rootContext->resolve(contextName);
 74.          corejavaContext 
 75.             = CosNaming::NamingContext::_narrow(obj);
 76.          if( CORBA::is_nil(corejavaContext) ) 
 77.          {
 78.             cerr << "Failed to narrow naming context." << endl;
 79.             return;
 80.          }
 81.       }
 82.
 83.       // Bind objref with given name to the context:
 84.       CosNaming::Name objectName;
 85.       objectName.length(1);
 86.       objectName[0].id   = name;
 87.       objectName[0].kind = (const char*) "Object"; 
 88.
 89.       try
 90.       {
 91.          corejavaContext->bind(objectName, objref);
 92.       }
 93.       catch(CosNaming::NamingContext::AlreadyBound& ex) 
 94.       {
 95.          corejavaContext->rebind(objectName, objref);
 96.       }
 97.    }
 98.    catch(CORBA::COMM_FAILURE& ex) 
 99.    {
100.       cerr 
101.          << "Caught system exception COMM_FAILURE -- unable to "
102.          << "contact the naming service." << endl;
103.    }
104.    catch(CORBA::SystemException&) 
105.    {
106.       cerr << "Caught a CORBA::SystemException while using the "
107.          << "naming service." << endl;
108.    }
109. }
110.
111. int main(int argc, char *argv[])
112. {
113.    cout << "Creating and initializing the ORB..." << endl;
114.
115.    CORBA::ORB_var orb = CORBA::ORB_init(argc, argv, "omniORB3");
116.
117.    CORBA::Object_var obj 
118.       = orb->resolve_initial_references("RootPOA");
119.    PortableServer::POA_var poa 
120.       = PortableServer::POA::_narrow(obj);
121.    poa->the_POAManager()->activate();
122.
123.    EnvImpl* envImpl = new EnvImpl();
124.    poa->activate_object(envImpl);
125.
126.    // Obtain a reference to the object, and register it in
127.    // the naming service.
128.    obj = envImpl->_this();
129.
130.    cout << orb->object_to_string(obj) << endl;
131.    cout << "Binding server implementations to registry..." 
132.       << endl;
133.    bindObjectToName(orb, "Env", obj);
134.    envImpl->_remove_ref();
135.
136.    cout << "Waiting for invocations from clients..." << endl;
137.    orb->run();
138.
139.    return 0;
140. }

Locating Objects Through IORs

If you can't configure your server ORB and name service so that your client can invoke it, you can still locate CORBA objects by using an Interoperable Object Reference, or IOR. An IOR is a long string starting with IOR: and followed by many hexadecimal digits, for example:

IOR:012020201000000049444c3a4163636f756e743a312e3000010000000
00000004e000000010100200f0000003231362e31352e3131322e31373900
20350420202e00000001504d43000000001000000049444c3a4163636f756
e743a312e30000e0000004a61636b20422e20517569636b00

An IOR describes an object uniquely. By convention, many server classes print out the IORs of all objects they register, to enable clients to locate them. You can then paste the server IOR into the client program. Specifically, use the following code:

String ref = "IOR:012020201000000049444c3a4163636f...";
   // paste IOR from server
org.omg.CORBA.Object object = orb.string_to_object(ref);

Then, narrow the returned object to the appropriate type, for example:

Env env = EnvHelper.narrow(object);

or

NamingContext context = NamingContextHelper.narrow(object);

When testing the code for this book, we successfully used this method to connect clients with Visibroker and OmniORB. (Some Java releases have bugs that prevent them from recognizing the OmniORB name service.)

org.omg.CORBA.ORB

graphics/api.gif
 

org.omg.CosNaming.NamingContext

graphics/api.gif
 

org.omg.CosNaming.NameComponent

graphics/api.gif
 

Implementing CORBA Servers

If you are deploying a CORBA infrastructure, you will find that the Java programming language is a good implementation language for CORBA server objects. The language binding is natural, and it is easier to build robust server software than with C++. This section describes how to implement a CORBA server in the Java programming language.

The example program in this section is similar to that of the preceding section. We supply a service to look up a system property of a Java virtual machine. Here is the IDL description:

interface SysProp
{
   string getProperty(in string name);
};

For example, our client test program calls the server as follows:

CORBA::String_var key = "java.vendor";
CORBA::String_var value = sysProp->getProperty(key);

The result is a string describing the vendor of the Java virtual machine that is executing the server program. We won't look into the details of the C++ client program. You will find the code in Example 5-24.

To implement the server, you run the idlj compiler with the -fall option. (By default, idlj only creates client-side stubs.)

idlj -fall SysProp.java

Then you extend the SysPropPOA class that the idlj compiler generated from the IDL file. Here is the implementation:

class SysPropImpl extends SysPropPOA
{
   public String getProperty(String key)
   {
      return System.getProperty(key);
   }
}

NOTE

graphics/note.gif
 

You can choose any name you like for the implementation class. In this book, we follow the RMI convention and use the suffix Impl for the implementation class name. Other programmers use a suffix Servant or _i.

NOTE

graphics/note.gif
 

If your implementation class already extends another class, you cannot simultaneously extend the implementation base class. In that case, you can instruct the idlj compiler to create a tie class. Your server class then implements the operations interface instead of extending the implementation base class. However, any server objects must be created by means of the tie class. For details, check out the idlj documentation at http://java.sun.com/j2se/1.4/docs/guide/idl/index.html.

Next, you need to write a server program that carries out the following tasks:

  1. Start the ORB.

  2. Locate and activate the root Portable Object Adaptor (POA).

  3. Create the server implementation.

  4. Use the POA to convert the servant reference to a CORBA object reference. (The server implementation class extends SysPropPOA which itself extends org.omg.PortableServer.Servant.)

  5. Print out its IOR (for name-service-challenged clients—see the Sidebar on page 400).

  6. Bind the server implementation to the naming service.

  7. Wait for invocations from clients.

You will find the complete code in Example 5-23. Here are the highlights.

You start the ORB as you would for a client program:

ORB orb = ORB.init(args, null);

Next, activate the root POA:

POA rootpoa 
   = (POA)orb.resolve_initial_references("RootPOA");
rootpoa.the_POAManager().activate();

Construct the server object and convert it to a CORBA object:

SysPropImpl impl = new SysPropImpl();
org.omg.CORBA.Object ref 
   = rootpoa.servant_to_reference(impl);

Next, obtain the IOR with the object_to_string method and print it out:

System.out.println(orb.object_to_string(impl));

You obtain a reference to the naming service in exactly the same way as with a client program:

org.omg.CORBA.Object namingContextObj =
   orb.resolve_initial_references("NameService");
NamingContext namingContext
   = NamingContextHelper.narrow(namingContextObj);

You then build up the desired name for the object. Here, we call the object SysProp:

NameComponent[] path =
   {
      new NameComponent("SysProp", "Object")

   };

CAUTION

graphics/caution.gif
 

We don't use a nested name because at the time of this writing, the orbd name service that is included in the Java SDK does not support nested names.

You use the rebind method to bind the object to the name:

namingContext.rebind(path, impl);

Finally, you wait for client invocations:

orb.run();

To test this program, do the following.

  1. Compile the IDL file, using both the C++ and Java IDL compilers.

  2. Compile the server program.

  3. Compile the C++ client program.

  4. Start the orbd naming service on the server. This program is a part of the Java SDK.

    orbd -ORBInitialPort 2809
    
  5. Start the server:

    java SysPropServer -ORBInitialPort 2809
    

    The server also runs until you kill it.

  6. Run the client.

    ./SysPropClient
    

    It should print out the JVM vendor of the server.

NOTE

graphics/note.gif
 

In this example, we use the transient name service. The orbd tool also includes a persistent name service that remembers names and object references even if the name service has been shut down and restarted. See the Java IDL documentation for more information on the persistent name service.

You have now seen how to use CORBA to connect clients and servers that were written in different programming languages. This concludes our discussion of CORBA. CORBA has a number of other interesting features, such as dynamic method invocation and a number of standard services such as transaction handling and persistence. We refer you to Client/Server Programming with Java and CORBA by Robert Orfali and Dan Harkey [John Wiley & Sons 1998] for an in-depth discussion of advanced CORBA issues.

Example 5-23 SysPropServer.java
 1. import org.omg.CosNaming.*;
 2. import org.omg.CORBA.*;
 3. import org.omg.PortableServer.*;
 4.
 5. class SysPropImpl extends SysPropPOA
 6. {
 7.    public String getProperty(String key)
 8.    {
 9.       return System.getProperty(key);
10.    }
11. }
12.
13. public class SysPropServer
14. {
15.    public static void main(String args[])
16.    {
17.       try
18.       {
19.          System.out.println(
20.             "Creating and initializing the ORB...");
21.
22.          ORB orb = ORB.init(args, null);
23.
24.          System.out.println(
25.             "Registering server implementation with the ORB...");
26.
27.          POA rootpoa 
28.             = (POA)orb.resolve_initial_references("RootPOA");
29.          rootpoa.the_POAManager().activate();
30.
31.          SysPropImpl impl = new SysPropImpl();
32.          org.omg.CORBA.Object ref 
33.             = rootpoa.servant_to_reference(impl);
34.
35.          System.out.println(orb.object_to_string(ref));
36.
37.          org.omg.CORBA.Object namingContextObj =
38.              orb.resolve_initial_references("NameService");
39.          NamingContext namingContext
40.             = NamingContextHelper.narrow(namingContextObj);
41.
42.          NameComponent[] path =
43.             {
44.                // new NameComponent("corejava", "Context"),
45.                new NameComponent("SysProp", "Object")
46.             };
47.
48.          System.out.println(
49.             "Binding server implementation to name service...");
50.
51.          namingContext.rebind(path, ref);
52.
53.          System.out.println(
54.             "Waiting for invocations from clients...");
55.          orb.run();
56.       }
57.       catch (Exception e)
58.       {
59.          e.printStackTrace(System.out);
60.       }
61.    }
62. }
Example 5-24 SysPropClient.cpp
 1. #include <iostream>
 2. #include "SysProp.hh"
 3.
 4. CORBA::Object_ptr getObjectReference(CORBA::ORB_ptr orb,
 5.    const char serviceName[])
 6. {
 7.    CosNaming::NamingContext_var rootContext;
 8.
 9.    try
10.    {
11.       // Obtain a reference to the root context of the 
12.       // name service:
13.       CORBA::Object_var initServ;
14.       initServ = orb->resolve_initial_references("NameService");
15.
16.       // Narrow the object returned by 
17.       // resolve_initial_references()
18.       // to a CosNaming::NamingContext object
19.       rootContext = CosNaming::NamingContext::_narrow(initServ);
20.       if (CORBA::is_nil(rootContext))
21.       {
22.          cerr << "Failed to narrow naming context." << endl;
23.          return CORBA::Object::_nil();
24.       }
25.    }
26.    catch(CORBA::ORB::InvalidName&)
27.    {
28.       cerr << "Name service does not exist." << endl;
29.       return CORBA::Object::_nil();
30.    }
31.
32.    // Create a name object, containing the name corejava/SysProp:
33.    CosNaming::Name name;
34.    name.length(1);
35.
36.    name[0].id   = serviceName;
37.    name[0].kind = "Object";
38.
39.    CORBA::Object_ptr obj;
40.    try
41.    {
42.       // Resolve the name to an object reference, and assign 
43.       // the returned reference to a CORBA::Object:
44.       obj = rootContext->resolve(name);
45.    }
46.    catch(CosNaming::NamingContext::NotFound&)
47.    {
48.       // This exception is thrown if any of the components of the
49.       // path [contexts or the object] aren't found:
50.       cerr << "Context not found." << endl;
51.       return CORBA::Object::_nil();
52.    }
53.    return obj;
54. }
55.
56. int main (int argc, char *argv[])
57. {
58.    CORBA::ORB_ptr orb = CORBA::ORB_init(argc, argv, "omniORB3");
59.
60.    CORBA::Object_var obj = getObjectReference(orb, "SysProp");
61.    SysProp_var sysProp = SysProp::_narrow(obj);
62.
63.    if (CORBA::is_nil(sysProp))
64.    {
65.       cerr << "hello: cannot invoke on a nil object reference." 
66.          << endl;
67.       return 1;
68.    }
69.
70.    CORBA::String_var key = "java.vendor";
71.    CORBA::String_var value = sysProp->getProperty(key);
72.
73.    cerr << key << "=" << value << endl;
74.
75.    return 0;
76. }

org.omg.CORBA.ORB

graphics/api.gif
 

org.omg.CosNaming.NamingContext

graphics/api.gif
 

CONTENTS